29 Oct 2022 (in calibre 6.8.0)
- Python templates can call stored templates and formatter functions.
You can call a Python template (PTM), a template language template (GPM), or built-in or user template functions. Syntax:
Code:
context.funcs.name(arguments)
For example, this python template uses the built-in template() function to format the title and authors. It then checks if the book is in a series, and if so appends the series name and the number of books in that series:
Code:
python:
def evaluate(book, context):
# Use the built-in template function to format the title and authors
x = context.funcs.template('{Title} - {authors}')
# Count the books in the series. First get the series name
series = book.get('series')
if series:
# The book is in a series. Get the count of books in that series
db = context.db.new_api
series_id = db.get_item_id('series', series)
book_count = len(db.books_for_field('series', series_id))
# Append the number of books to the title - author string
x = x + f' --- In the series "{series}, which has {book_count} book{"s" if book_count > 1 else ""}'
else:
x = x + " --- This book isn't in a series"
return x
This screen capture shows the results:

If a function or template name name is also a Python keyword then append an underscore, as in 'template_()'
- Breakpoints for Python templates in the Template tester dialog.
