bronx.stdtypes.xtemplates

A templating system for nested dictionaries and lists.

The DefaultTemplate class should be used directly. See its documentation.

Classes

class bronx.stdtypes.xtemplates.DefaultTemplate(base)[source]

Bases: object

Recursively walk into nested dictionaries and/or lists templates.

This templating class provides two features:

  • String substitution: If a string looks like {{some_statement}}, some_statement is evaluated and the returned data replaces the original string.

  • Loop expansion: Portions of the template will be duplicated according to a loop iterator (see below for more details).

The use of this class is very simple: create an object by providing the nested dictionaries and/or lists template. Then, call the render() method with a list of variables that will be used when processing the template.

Example:

>>> tpl = ['Any static string.',
...        dict(inputs=dict(__bronx_tpl_engine__='loop',
...                         __loopiterator__='zip(members, physics)',
...                         __loopvariables__='member, physic',
...                         __body__=dict(kind='member_spec',
...                                       msg=('{{"Member number: {:03d} next one is {!s}"' +
...                                            '.format(member, member_next)}}'),
...                                       member='{{member}}',
...                                       physic_id='{{physic}}',
...                                       terms=dict(__bronx_tpl_engine__='loop',
...                                                  __loopiterator__='enumerate(terms)',
...                                                  __loopvariables__='i, term',
...                                                  __body__=['{{i}}', '{{term.fmthm}}']),
...                                       )
...                         ),
...             nmembers='{{len(members)}}',
...             nterms='{{len(terms)}}'
...             ),
...        ]
>>> dt = DefaultTemplate(tpl)
>>> from bronx.stdtypes.date import Time
>>> tpl_r = dt.render(members=[1, 2, 3],
...                   physics=['turb1', 'turb2', 'turb3'],
...                   terms=[Time(3, 0), Time(6, 0)])
>>> (tpl_r ==
...  ['Any static string.',
...   {'inputs': [{'kind': 'member_spec',
...                'member': 1,
...                'msg': 'Member number: 001 next one is 2',
...                'physic_id': 'turb1',
...                'terms': [[0, '0003:00'], [1, '0006:00']]},
...               {'kind': 'member_spec',
...                'member': 2,
...                'msg': 'Member number: 002 next one is 3',
...                'physic_id': 'turb2',
...                'terms': [[0, '0003:00'], [1, '0006:00']]},
...               {'kind': 'member_spec',
...                'member': 3,
...                'msg': 'Member number: 003 next one is None',
...                'physic_id': 'turb3',
...                'terms': [[0, '0003:00'], [1, '0006:00']]}],
...    'nmembers': 3,
...    'nterms': 2}])
True

Note

More details on loop expansion:

  • The loop expansion is triggered by a dictionary that contains the __bronx_tpl_engine__ = 'loop' entry;

  • The __loopiterator__ (mandatory) item is a python code statement that returns any kind of iterable objects. The loop will iterate on it;

  • The __loopvariables__ (mandatory) item is a comma-separated list where the loop control variable names are specified. These control variables, will be updated at each iteration of the loop with the current value of the iterator. In addition, variables suffixed by _prev and _next will contain the previous and next iterator items;

  • The __body__ (mandatory) item will be duplicated at each iteration of the loop;

  • The __body_first__ and __body_last__ (optional) items may be added in order to specify a specfic body for respectively the first and last iteration of the loop;

  • The __extra_vars__ (optional) item is a dictionary that contains variable names (keys) associated with a Python code statement (values). These variables will be evaluated at each iteration of the loop and could be used later on in string substitutions.

Note

It heavily relies on Python code statements that are checked and evaluate using the bronx.syntax.minieval module. Consequently, exceptions based on bronx.syntax.minieval.SingleLineStatementError may be raised.

Parameters:

tpl – The template to work with (nested dictionaries and/or lists)

render(**kwargs)[source]

Renders the template for a specific set kwargs of variables.

Parameters:

kwargs – Variables usable during template rendering

Returns:

The processed template

Raises:

Exceptions

exception bronx.stdtypes.xtemplates.TemplateLoopRenderingError(msg)[source]

Bases: TemplateRenderingError

Any exception raised by the DefaultTemplate class. during loop expansion

exception bronx.stdtypes.xtemplates.TemplateRenderingError[source]

Bases: ValueError

Any exception raised by the DefaultTemplate class.