Skip to main content

Handlebars.js templating for Python 3 and 2

Project description

Pybars3 provides a template system for Python which is compatible with Handlebars.js. It is a fork of the pybars project that adds Python 3 compatibility and numerous features from Handlebars.js 2.0.

Handlebars.js Compatibility

This is somewhat of a side-project of mine (@wbond) that is maintained for almost purely pragmatic reasons. I want to share templates between the server and client-side, and I need something more powerful than Mustache.

So, with that information, you should realize that the code is probably messy, that I am certain there are bugs, and select features from different versions of Handlebars are ported as I or other contributors need them.

Here is a partial list of features that are supported:

  • @root root data accesor (Handlebars 2.0)

  • @_parent parent scope accesor (Handlebars 2.0)

  • ../ parent scope accessor

  • @index, @key (Handlebars 1.0, 1.2)

  • @first and @last data element in the #each helper (Handlebars 1.1)

  • kwargs passed to partials (Handlebars 2.0)

  • @../index syntax for accessing parent scope data items (Handlebars 2.0)

Features not currently implemented:

  • Complex paths (../name/../name)

  • Subexpresions (Handlebars 1.3)

  • Whitespace control, {{var~}} (Handlebars 1.1)

  • Lines containing old block statements and whitespace are not removed (Handlebars 2.0)

Feel free to jump in with issues or pull requests.

Usage

For details on the template language see the http://handlebarsjs.com documentation.

Typical usage:

# Get a compiler
from pybars import Compiler
compiler = Compiler()

# Compile the template
source = u"{{>header}}{{#list people}}{{firstName}} {{lastName}}{{/list}}"
template = compiler.compile(source)

# Add any special helpers
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
helpers = {'list': _list}

# Add partials
header = compiler.compile('<h1>People</h1>')
partials = {'header': header}

# Render the template
output = template({
    'people': [
        {'firstName': "Yehuda", 'lastName': "Katz"},
        {'firstName': "Carl", 'lastName': "Lerche"},
        {'firstName': "Alan", 'lastName': "Johnson"}
    ]}, helpers=helpers, partials=partials)

print(output)

The generated output will be:

<h1>People</h1><ul><li>Yehuda Katz</li><li>Carl Lerche</li><li>Alan Johnson</li></ul>

Handlers

Translating the engine to python required slightly different calling conventions to the JS version:

  • block helpers should accept this, options, *args, **kwargs

  • other helpers should accept this, *args, **kwargs

  • closures in the context should accept this, *args, **kwargs

A template like {{foo bar quux=1}} will pass bar as a positional argument and quux as a keyword argument. Keyword arguments have to be non-reserved words in Python. For instance, print as a keyword argument will fail.

Implementation Notes

Templates with literal boolean arguments like {{foo true}} will have the argument mapped to Python’s True or False as appropriate.

For efficiency, rather that passing strings round, pybars passes a subclass of list (strlist) which has a __unicode__ implementation that returns u"".join(self). Template helpers can return any of list, tuple, unicode or strlist instances. strlist exists to avoid quadratic overheads in string processing during template rendering. Helpers that are in inner loops should return list or strlist for the same reason.

NOTE The strlist takes the position of SafeString in the js implementation: when returning a strlist it will not be escaped, even in a regular {{}} expansion.

import pybars

source = u"{{bold name}}"

compiler = pybars.Compiler()
template = compiler.compile(source)

def _bold(this, name):
    return pybars.strlist(['<strong>', name, '</strong>'])
helpers = {'bold': _bold}

output = template({'name': 'Will'}, helpers=helpers)
print(output)

The data facility from the JS implementation has not been ported at this point, if there is demand for it it would be quite easy to add. Similarly the stringParams feature has not been ported - quote anything you wish to force to a string in a helper call.

Dependencies

  • Python 2.6-2.7, 3.3+

  • PyMeta3

Testing Dependencies

Development

Upstream development takes place at https://launchpad.net/pybars.

To run the tests use the runner of your choice, the test suite is pybars.tests.test_suite.

For instance:

python -m testtools.run pybars.tests.test_suite

pybars is testrepository enabled, so you can just do:

testr init
testr run

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pybars3-0.5.0.tar.gz (19.7 kB view details)

Uploaded Source

File details

Details for the file pybars3-0.5.0.tar.gz.

File metadata

  • Download URL: pybars3-0.5.0.tar.gz
  • Upload date:
  • Size: 19.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No

File hashes

Hashes for pybars3-0.5.0.tar.gz
Algorithm Hash digest
SHA256 f70b1a9550245f36a201c759d169d6e09337098ec9f0b70c718cfae2d95c9eaa
MD5 150273652a15164bbaa4cdfc0606b3fe
BLAKE2b-256 f4526db3809b3dafb1e098c49a771c980d0df029e78402d51ba2bf52f04cdea4

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page