I added the ability to use custom python context classes. The change is in calibre source.
How to use:
- Create a subclass of utils.formatter.PythonTemplateContext. Add whatever you want to it.
- Pass an instance of your class to the formatter using
Code:
python_context_object=whatever
as in
Code:
formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi,
python_context_object=CustomContext())
- If you want something to happen when the object is used, override
Code:
set_values(**kwargs)
This method is called just before executing the template, providing the known attributes db, globals, and arguments. Be sure to call the superclass method.
Here is an example test of the new feature:
Code:
template = '''python:
def evaluate(book, ctx):
tags = ctx.db.new_api.all_field_names('tags')
return ','.join(list(ctx.helper_function(tags)))
'''
from calibre.utils.formatter import PythonTemplateContext
class CustomContext(PythonTemplateContext):
def helper_function(self, arg):
s = set(arg)
s.add('helper called')
return s
v = formatter.safe_format(template, {}, 'TEMPLATE ERROR', mi,
python_context_object=CustomContext())
self.assertEqual(set(v.split(',')), {'Tag One', 'News', 'Tag Two','helper called'})