Pybars3

0.9.7 · maintenance · verified Thu Apr 16

Pybars3 is a Python library that provides a templating system compatible with Handlebars.js, supporting both Python 2 and Python 3. It is a fork of the original `pybars` project, enhancing it with Python 3 compatibility and features from Handlebars.js up to version 2.0. The current version is 0.9.7, released in November 2019, indicating an infrequent release cadence and a status of maintenance.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates compiling a Handlebars template, registering a custom block helper, defining a partial, and rendering the template with contextual data. Note the use of `u""` for template strings for compatibility, though on Python 3 plain strings are sufficient.

from pybars import Compiler

# Get a compiler
compiler = Compiler()

# Define a helper function
def _list_helper(this, options, items):
    result = ['<ul>']
    for item in items:
        result.append('<li>')
        result.extend(options['fn'](item)) # Render the inner block
        result.append('</li>')
    result.append('</ul>')
    return result

# Register helpers and partials
helpers = {'list': _list_helper}
header_template = compiler.compile(u'<h1>{{title}}</h1>')
partials = {'header': header_template}

# Compile the main template source
source = u"""
{{>header}}
<p>Hello, {{name}}!</p>
{{#list people}}{{firstName}} {{lastName}}{{/list}}
"""
template = compiler.compile(source)

# Data to render
data = {
    'title': 'People List',
    'name': 'World',
    'people': [
        {'firstName': 'Yehuda', 'lastName': 'Katz'},
        {'firstName': 'Carl', 'lastName': 'Lerche'},
        {'firstName': 'Alan', 'lastName': 'Johnson'}
    ]
}

# Render the template
output = template(data, helpers=helpers, partials=partials)
print(output)

view raw JSON →