Quote:
Originally Posted by smoothrolla
is there any documentation on how to use mi and formatter? i have struggled to find any!
thanks
|
The API for mi is documented in
http://manual.calibre-ebook.com/template_ref.html#id73.
The only formatter method that is 'public' is
Code:
safe_format(self, fmt, kwargs, error_value, book)
- fmt: the template string to evaluate
- kwargs: a dict object containing key => value pairs. This is almost always the same as 'book' (below), but it can be different.
- error_value: a string that is used if the template throws an exception
- book: the metadata for the book in question, passed as mi to a formatter function. Can be None. Usually is the same as kwargs.
Notes:
- kwargs is not always an mi structure. It should be accessed using
Code:
kwargs.get('key', defaultValue)
where 'key' is the lookup key for the field/column in question.
- book is either None or an instance of Metadata. There is no guarantee that the values obtained from book.get (mi.get) are the same as those returned by kwargs.get, although they usually are.
- book does not equal kwargs for templates used in save-to-disk.
- book does equal kwargs for templates used in the gui
- book may or may not equal kwargs for templates used in send-to-device.
- calling the formatter from a template function will evaluate the sub-template in the current context, sharing local template variables. If you don't want that, then create a new instance of formatter.
Code:
formatter.__class__().safe_format('yourTemplateString', kwargs, 'YourErrorText', mi)
Taking the above and defensive programming into consideration, the template I provided earlier is better written as
Code:
def evaluate(self, formatter, kwargs, mi, locals):
x = kwargs.get('pubdate', None)
if x is None:
return ''
x = (x.year/10)*10
return '%04d'%x
If it matters to your task, you can check if you can use mi instead of kwargs by testing if kwargs == mi. You can check if kwargs is an instance if Metadata using
Code:
from calibre.ebooks.metadata.book.base import Metadata
if isinstance(kwargs, Metadata):
do what you want to do
Finally, the best way to learn how to use these things is to look at the calibre source. See
http://manual.calibre-ebook.com/develop.html. For example, mi makes reference to Field_Metadata, a dict describing each field/column in the calibre database. This dict is documented in src.calibre.library.field_metadata.py.