View Single Post
Old 11-01-2022, 11:26 AM   #96
chaley
Grand Sorcerer
chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.chaley ought to be getting tired of karma fortunes by now.
 
Posts: 12,495
Karma: 8065348
Join Date: Jan 2010
Location: Notts, England
Device: Kobo Libra 2
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:
    Click image for larger version

Name:	Clipboard03.png
Views:	3722
Size:	52.6 KB
ID:	197492

    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.
    Click image for larger version

Name:	Clipboard02.png
Views:	3735
Size:	57.8 KB
ID:	197491

Last edited by chaley; 11-15-2022 at 01:23 PM.
chaley is offline   Reply With Quote