Quote:
Originally Posted by capink
Just to be sure we are on the same page, I will define a global dict for each chain, which have some predefined values and also allows the user to insert his own arbitrary variables
Code:
self.global = {
_chain_name: ....,
_action_name: ....,
user_var1: ......,
......
}
Some of the above variables will be overwritten for each action. And this global dict will be used for condition testing as well.
|
Yes
Quote:
The user can access this using a template like this:
Code:
program: globals('user_var1')
|
Not quite. The variable name parameters are not quoted, as in globals(user_var1). This defines a template local variable named user_var1.
Note that
Code:
program: globals(user_var1='some_default')
is also valid, as is this TPM template
Code:
{somefield:'globals(user_var1);'rest of template''}
Quote:
Whenever a template is being evaluated, I should pass this dict to the formatter, may something like this:
Code:
template_output = SafeFormat().safe_format(template, mi, TEMPLATE_ERROR, mi, chain_loop.global)
|
I went ahead and implemented globals in the formatter. The safe_format parameter signature is now:
Code:
def safe_format(self, fmt, kwargs, error_value, book,
column_name=None, template_cache=None,
strip_results=True, template_functions=None,
global_vars={}):
Using your example you would call it like this:
Code:
template_output = SafeFormat().safe_format(template, mi, TEMPLATE_ERROR,
mi, global_vars=chain_loop.global)
Quote:
When testing for conditions, if an action does not define any condition it will always execute. For actions that define conditions, they must be evaluated against the value in the global dict, and if they match, the action will run, otherwise it will be skipped.
|
Sounds good. One question: what if the value isn't in the dict? Is that an error or no match?
If you run from source, attached is a version of calibre.utils.formatter.py that implements globals.
For fun, it also implements for loops. Example:
Code:
for v in expression:
statement [; statement]*
rof
The expression can return a field name, for example 'tags', or it can return a comma-separated list of values. The variable v is set to a value then the statement list is executed. Of course, 'v' can be any variable name.
EDIT: I will submit the formatter changes to Kovid if you think they work for you.
EDIT 2: Replaced the attachment. I had left a print statement in the original.
EDIT 3: Removed the attachment now that the files are in the official calibre source.