pybars is a module that provides a template system for Python which is compatible with handlebars.js.
Usage
For details on the template language see the http://handlebarsjs.com/ documentation.
Inline closures are not supported: the primary use case for pybars is allowing server side rendering of a handlebars.js template in a Python appserver; this isn't possible if the template includes inline-javascript, nor would client side rendering be possible if inline Python was included. Use external helpers to achieve the same effect.
A key difference to the js version deserves special mention: templates return a subclass of list ('liststr') which has a __unicode__ implementation that returns u"".join(self). Template helpers can return any of list, tuple, unicode or liststr instances. liststr exists to avoid quadratic overheads in string processing during template rendering. Helpers that are in inner loops should return list or liststr for the same reason.
NOTE: The liststr takes the position of SafeString in the js implementation: when returning a liststr it will not be escaped, even in a regular {{}} expansion.
Typical usage:
Grab a compiler:
>>> from pybars import Compiler
>>> compiler = Compiler()
Register any extensions you need:
>>> def _list(this, options, items):
... result = [u'< ul >']
... for thing in items:
... result.append(u'< li >')
... result.extend(options['fn'](thing))
... result.append(u'< /li >')
... result.append(u'< /ul >')
... return result
>>> compiler.register_helper(u'list', _list)
And compile your template:
>>> source = u"{{#list people}}{{firstName}} {{lastName}}{{/list}}"
>>> template = compiler.compile(source)
You can now render it:
>>> template({
... 'people': [
... {'firstName': "Yehuda", 'lastName': "Katz"},
... {'firstName': "Carl", 'lastName': "Lerche"},
... {'firstName': "Alan", 'lastName': "Johnson"}
... ]})
< ul >< li >Yehuda Katz< /li >< li >Carl Lerche< /li >< li >Alan Johnson< /li >< /ul >
More details should be found by reading the API docs (e.g. pydoc pybars).
Installation
Either run setup.py in an environment with all the dependencies available, or add the working directory to your PYTHONPATH.
Development
Upstream development takes place at https://launchpad.net/pybars. To setup a working area for development, if the dependencies are not immediately available, you can use ./bootstrap.py to create bin/buildout, then bin/py to get a python interpreter with the dependencies available.
To run the tests use the runner of your choice, the test suite is pybars.tests.test_suite.
For instance:
bin/py -m testtools.run pybars.tests.test_suite
pybars is testrepository enabled, so you can just do:
testr init $ testr run
Product's homepage
Requirements:
· Python
· PyMeta
· python-subunit
· testtools