• Stars
    star
    175
  • Rank 218,059 (Top 5 %)
  • Language
    Python
  • License
    GNU Lesser Genera...
  • Created over 11 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Handlebars.js template support for Python 3 and 2

pybars3 - Handlebars.js for Python 3 and 2

Build Status Codecov

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.

Installation

pip install pybars3

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)
  • pybars.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 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(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, 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

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

Copyright

Copyright (c) 2015 Will Bond, Mjumbe Wawatu Ukweli, 2012 Canonical Ltd

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, version 3 only.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
GNU Lesser General Public License version 3 (see the file LICENSE).

More Repositories

1

package_control

The Sublime Text package manager
Python
4,781
star
2

package_control_channel

Default channel file for Package Control. Follow the directions at:
Python
1,243
star
3

sublime_terminal

Launch terminals from the current file or the root project folder
Python
596
star
4

sublime_alignment

Easy alignment of multiple selections and multi-line selections
Python
521
star
5

asn1crypto

Python ASN.1 library with a focus on performance and a pythonic API
Python
329
star
6

oscrypto

Compiler-free Python crypto library backed by the OS, supporting CPython and PyPy
Python
321
star
7

sublime_prefixr

A Sublime Text 2 plugin that runs CSS through the Prefixr API
Python
199
star
8

packagecontrol.io

The Package Control website
Python
110
star
9

certvalidator

Python library for validating X.509 certificates and paths
Python
106
star
10

md5-js

A modification of Joseph Myers's high-preformance javascript md5 function that hashes unicode characters by first converting to UTF-8. http://jsperf.com/md5-shootout
JavaScript
98
star
11

vat_moss-python

A Python library for dealing with VAT MOSS and Norway VAT on digital services. Includes VAT ID validation, rate calculation based on place of supply, exchange rate and currency tools for invoices.
Python
65
star
12

mtmux

A script that uses tmux for multi-server administration with a tiling interface and synchronized keyboard input along the lines of terminator, clusterssh, multi-gnome-terminal, pconsole, etc.
Shell
51
star
13

vat-moss.js

A Javascript library for dealing with VAT MOSS and Norway VAT on digital services. Includes VAT ID checking, rate calculation based on place of supply, exchange rate and currency tools for invoices.
JavaScript
51
star
14

puremagic

A pure lua module for detecting the mime type of a file based on the contents - inspired by libmagic
Lua
38
star
15

certbuilder

Python library for generating and signing X.509 certificates
Python
34
star
16

ocspbuilder

Python library for generating OCSP requests and responses
Python
32
star
17

badtls.io

Keys, certificates, scripts and configuration for badtls.io
Python
27
star
18

sublime_tortoise

Keyboard shortcuts and menu entries to execute TortoiseSVN, TortoiseHg and TortoiseGit commands
Python
26
star
19

pi-github-runner

Docker config to easily enable arm and arm64 GitHub Actions via the self-hosted runner mechanism
Shell
24
star
20

pymeta3

A Python 3 compatible fork of https://launchpad.net/pymeta
Python
18
star
21

csrbuilder

Python library for generating certificate signing requests (CSRs)
Python
18
star
22

crc32-js-php

A javascript function and PHP snippet that produce identical crc32 checksums
JavaScript
17
star
23

crlbuilder

Python library for creating and signing certificate revocation lists (CRLs)
Python
16
star
24

swift-for-sublime

A modern Swift (5.6) syntax definition for Sublime Text 4
Swift
15
star
25

ChannelRepositoryTools

A Sublime Text package for working with channels and repositories
Python
11
star
26

sublime-sql-tmlanguage

A fork of the default SQL.tmLanguage with support for SQL Server data types and functions
9
star
27

shadow_password_crypt

A python script that generates sha512 password hashes suitable for use with useradd(8)
Python
5
star
28

wbond

4
star
29

SublimeSyntaxHTMLColorizer

Python
4
star
30

unittest_data

A pair of decorators to add data providers/test generators to unittest in Python 2.6, 2.7, 3.3 and 3.4
Python
3
star
31

subversion-cross-compile

Scripts to cross-compile Subversion 1.6, 1.7 and 1.8 from Linux/OS X to Windows
C
2
star
32

handlebars.py

MIT-licensed port of Handlebars.js to Python
Python
2
star
33

package_control-json

A repo to host repository and channel JSON files for testing Package Control
2
star
34

subversion

A fork of subversion that handle localization of dates on windows by only using numbers
C
2
star
35

gears-libsass

Python
1
star