Skip to main content

python-handlebars - Handlebars.js for Python 3

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

This project is strongly inspired in Pybars3.

Installation

pip install python-handlebars

Handlebars.js Compatibility

This is somewhat of a side-project for the current developers, and is maintained for almost purely pragmatic reasons. Being able to share templates between the server and client-side is very useful, and we like having something more powerful than Mustache.

So, with that information, you should realize that the code is probably messy, that there are certainly bugs and not all of Handlebars 2.0, or even 1.1 is currently implemented.

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)
  • {{[segment literal notation]}} for paths that contain non-word chars (Handlebars 1.1)
  • {{> "quoted partial name"}} for partials that contain non-word chars (Handlebars 1.1)
  • lookup helper for dynamic name access (Handlebars 2.0)
  • Subexpresions (Handlebars 1.3)
  • Lines containing only block statements and whitespace are removed (Handlebars 2.0)
  • handlebars.Compiler().precompile() that is equivalent to Handlebars.precompile()
  • {{> (whichPartial) }} dynamic partials (Handlebars 3.0)
  • {{{{raw}}}}{{escaped}}{{{{/raw}}}} raw blocks (Handlebars 2.0)
  • Whitespace control, {{var~}} (Handlebars 1.1)

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 handlebars 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(u'<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, handlebars 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 handlebars

source = u"{{bold name}}"

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

def _bold(this, name):
    return handlebars.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 3.8+
  • Python-OMeta

Development

Running tests:

python tests.py

To display the AST and generated Python code, execute:

python tests.py --debug

To run a specific test:

python tests.py TestAcceptance.test_subexpression

Or to debug a specific test:

python tests.py --debug TestAcceptance.test_subexpression

Metadata

Release files for python-handlebars 0.0.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for python-handlebars 0.0.3
File Size Uploaded Provenance
python_handlebars-0.0.3.tar.gz 31.5 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for python-handlebars 0.0.3
File Interpreter ABI Platform
python_handlebars-0.0.3-py3-none-any.whl Python 3 none any Details

Total release size: 47.9 kB

Release files / python_handlebars-0.0.3.tar.gz

Download URL python_handlebars-0.0.3.tar.gz
Size 31.5 kB
Tags Source
SHA-256 checksum
How to use checksums
7645b77600475ecd40e15e9abe3f4aecf3092b698673bee52a98d41f136c4f97
BLAKE2b-256 checksum
How to use checksums
9e4944befc1fd566cc7779b34307a5fe6e6e47747505dc4984085e97664ee1ae
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.12.2

Release files / python_handlebars-0.0.3-py3-none-any.whl

Download URL python_handlebars-0.0.3-py3-none-any.whl
Size 16.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3f2474acb0736e51c221d5f39854df5a95d662d9af87109317f8eb1b32da5a60
BLAKE2b-256 checksum
How to use checksums
ca9df99ef7d7816e3e1e2234d44c5b236c3796f848701edcc81db8f5ec0454e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.1.1 CPython/3.12.2

Security for python-handlebars 0.0.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page