Pystache
This updated fork of Pystache is currently tested on Python 3.8+ and in Conda, on Linux, Macos, and Windows (Python 2.7 is no longer supported).
Pystache is a Python implementation of Mustache. Mustache is a framework-agnostic, logic-free templating system inspired by ctemplate and et. Like ctemplate, Mustache “emphasizes separating logic from presentation: it is impossible to embed application logic in this template language.”
The mustache(5) man page provides a good introduction to Mustache’s syntax. For a more complete (and more current) description of Mustache’s behavior, see the official Mustache spec.
Pystache is semantically versioned and older versions can still be found on PyPI. This version of Pystache now passes all tests in version 1.1.3 of the spec.
Requirements
Pystache is tested with:
Python 3.8
Python 3.9
Python 3.10
Python 3.11
Conda (py38 and py310)
JSON support is needed only for the command-line interface and to run the spec tests; PyYAML can still be used (see the Develop section).
Official support for Python 2 has ended with Pystache version 0.6.0.
Note
This project uses setuptools_scm to generate and maintain the version file, which only gets included in the sdist/wheel packages. In a fresh clone, running any of the tox commands should generate the current version file.
Quick Start
Be sure to get the latest release from either Pypi or Github.
Install It
From Pypi:
$ pip install pystache
Or Github:
$ pip install -U pystache -f https://github.com/PennyDreadfulMTG/pystache/releases/
And test it:
$ pystache-test
To install and test from source (e.g. from GitHub), see the Develop section.
Use It
Open a python console:
>>> import pystache
>>> print(pystache.render('Hi {{person}}!', {'person': 'Mom'}))
Hi Mom!
You can also create dedicated view classes to hold your view logic.
Here’s your view class (in ../pystache/tests/examples/readme.py):
class SayHello(object):
def to(self):
return "Pizza"
Instantiating like so:
>>> from pystache.tests.examples.readme import SayHello
>>> hello = SayHello()
Then your template, say_hello.mustache (by default in the same directory as your class definition):
Hello, {{to}}!
Pull it together:
>>> renderer = pystache.Renderer()
>>> print(renderer.render(hello))
Hello, Pizza!
For greater control over rendering (e.g. to specify a custom template
directory), use the Renderer
class like above. One can pass
attributes to the Renderer class constructor or set them on a Renderer
instance. To customize template loading on a per-view basis, subclass
TemplateSpec
. See the docstrings of the
Renderer
class and
TemplateSpec
class for more information.
You can also pre-parse a template:
>>> parsed = pystache.parse(u"Hey {{#who}}{{.}}!{{/who}}")
>>> print(parsed)
['Hey ', _SectionNode(key='who', index_begin=12, index_end=18, parsed=[_EscapeNode(key='.'), '!'])]
And then:
>>> print(renderer.render(parsed, {'who': 'Pops'}))
Hey Pops!
>>> print(renderer.render(parsed, {'who': 'you'}))
Hey you!
Unicode
This section describes how Pystache handles unicode, strings, and encodings.
Internally, Pystache uses only unicode strings (str
in Python 3).
For input, Pystache accepts byte strings (bytes
in Python 3).
For output, Pystache’s template rendering methods return only unicode.
Pystache’s Renderer
class supports a number of attributes to control
how Pystache converts byte strings to unicode on input. These include
the file_encoding
, string_encoding
, and decode_errors
attributes.
The file_encoding
attribute is the encoding the renderer uses to
convert to unicode any files read from the file system. Similarly,
string_encoding
is the encoding the renderer uses to convert any other
byte strings encountered during the rendering process into unicode (e.g.
context values that are encoded byte strings).
The decode_errors
attribute is what the renderer passes as the
errors
argument to Python’s built-in unicode-decoding function
(str()
in Python 3). The valid values for this argument are
strict
, ignore
, and replace
.
Each of these attributes can be set via the Renderer
class’s
constructor using a keyword argument of the same name. See the Renderer
class’s docstrings for further details. In addition, the file_encoding
attribute can be controlled on a per-view basis by subclassing the
TemplateSpec
class. When not specified explicitly, these attributes
default to values set in Pystache’s defaults
module.
Develop
To test from a source distribution (without installing):
$ python test_pystache.py
To test Pystache with multiple versions of Python (with a single command!) and different platforms, you can use [tox](https://pypi.python.org/pypi/tox):
$ pip install tox
$ tox -e py
To run tests on multiple versions with coverage, run:
$ tox -e py38-linux,py39-linux # for example
(substitute your platform above, eg, macos or windows)
The source distribution tests also include doctests and tests from the Mustache spec. To include tests from the Mustache spec in your test runs:
$ git submodule update --init
The test harness parses the spec’s (more human-readable) yaml files if PyYAML is present. Otherwise, it parses the json files. To install PyYAML:
$ pip install pyyaml # note this is installed automatically by tox
Once the submodule is available, you can run the full test set with:
$ tox -e setup -- ext/spec/specs
Making Changes & Contributing
We use the gitchangelog action to generate our github Release page, as well as the gitchangelog message format to help it categorize/filter commits for a tidier release page. Please use the appropriate ACTION modifiers in any Pull Requests.
This repo is also pre-commit enabled for various linting and format checks. The checks run automatically on commit and will fail the commit (if not clean) with some checks performing simple file corrections.
If other checks fail on commit, the failure display should explain the error
types and line numbers. Note you must fix any fatal errors for the
commit to succeed; some errors should be fixed automatically (use
git status
and git diff
to review any changes).
Note pylint
is the primary check that requires your own input, as well
as a decision as to the appropriate fix action. You must fix any pylint
warnings (relative to the baseline config score) for the commit to succeed.
See the following pages for more information on gitchangelog and pre-commit.
You will need to install pre-commit before contributing any changes; installing it using your system’s package manager is recommended, otherwise install with pip into your usual virtual environment using something like:
$ sudo emerge pre-commit --or--
$ pip install pre-commit
then install it into the repo you just cloned:
$ git clone https://github.com/PennyDreadfulMTG/pystache
$ cd pystache/
$ pre-commit install
It’s usually a good idea to update the hooks to the latest version:
pre-commit autoupdate
Mailing List (old)
There is(was) a mailing list. Note that there is a bit of a delay between posting a message and seeing it appear in the mailing list archive.
Credits
>>> import pystache
>>> context = { 'author': 'Chris Wanstrath', 'maintainer': 'Chris Jerdonek','refurbisher': 'Steve Arnold', 'new_maintainer': 'Thomas David Baker' }
>>> print(pystache.render("Author: {{author}}\nMaintainer: {{maintainer}}\nRefurbisher: {{refurbisher}}\nNew maintainer: {{new_maintainer}}", context))
Author: Chris Wanstrath
Maintainer: Chris Jerdonek
Refurbisher: Steve Arnold
New maintainer: Thomas David Baker
Pystache logo by David Phillips is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Change history (recent)
v0.6.5 (2023-08-26)
Bump the version bits called out in the readme. [Stephen L Arnold]
Keep changelog up to date manually as I don’t know how to autogenerate. [Thomas David Baker]
v0.6.4 (2023-08-13)
Other
Merge pull request #23 from PennyDreadfulMTG/more-fixes. [Thomas David Baker]
Use the content-type for RST that pypi now wants
Use the content-type for RST that pypi now wants. [Thomas David Baker]
v0.6.3 (2023-08-13)
New
- Add full sphinx apidoc build, include readme/extras. [Stephen L Arnold]
add new tox commands for ‘docs’ and ‘docs-lint’
cleanup link errors found by docs-lint
add sphinx doc build workflow, update ci workflow
remove new version var from init.py globals
- Display repo state in docs build, include CHANGELOG. [Stephen L Arnold]
add sphinx_git extension to docs conf and setup deps
display branch/commit/state docs were built from
include CHANGELOG (but not HISTORY) in docs build/toc
Convert readme.md to readme.rst, move extra docs. [Stephen L Arnold]
Fixes
Fix included filename and link cleanup. [Stephen L Arnold]
Remove more py2 cruft from doctesting (py3.10 warnings) [Stephen L Arnold]
- Update maintainer info and spec test cmd. [Stephen L Arnold]
update coverage value for delta/base, allow digits only
- Use updated bandit action and workflow excludes (exclude test) [Stephen L Arnold]
also fix missing PR event check in coverage workflow
- Use current org-level coverage workflow. [Stephen L Arnold]
increase fetch depth and update regex
updated action deps, relaxed run criteria
go back to “normal” tokens, remove permission hacks
still needs more job isolation => refactor for another day
Other
Merge pull request #21 from PennyDreadfulMTG/update-pypi. [Thomas David Baker]
Update a few small things before making a release for pypi
Update location of flake8 for pre-commit, official location has moved. [Thomas David Baker]
Correct small issue in README. [Thomas David Baker]
Specify passenv in a way that tox is happy with. [Thomas David Baker]
Ignore PyCharm dir. [Thomas David Baker]
Update TODO to remove some things that have been TODOne. [Thomas David Baker]
Merge pull request #20 from VCTLabs/new-docs-cleanup. [Katelyn Gigante]
New docs cleanup
Merge pull request #19 from VCTLabs/auto-docs. [Thomas David Baker]
New docs and automation, more modernization
- Do pre-release (manual) updates for changes and conda recipe. [Stephen L Arnold]
create changes file: gitchangelog v0.6.0.. > CHANGELOG.rst
edit top line in CHANGELOG.rst using current date/new tag
edit conda/meta.yaml using new tag, then tag this commit
Merge pull request #18 from VCTLabs/mst-upstream. [Thomas David Baker]
Workflow and test driver fixes
Use buildbot account. [Katelyn Gigante]
Merge pull request #16 from PennyDreadfulMTG/fix-coverage. [Katelyn Gigante]
Use ACCESS_TOKEN secret rather than provided GITHUB_TOKEN
Use ACCESS_TOKEN secret rather than provided GITHUB_TOKEN. [Katelyn Gigante]
Should fix the coverage badge
v0.6.2 (2022-09-14)
New
Add full sphinx apidoc build, include readme/extras. [Stephen L Arnold]
add new tox commands for ‘docs’ and ‘docs-lint’
cleanup link errors found by docs-lint
add sphinx doc build workflow, update ci workflow
remove new version var from __init__.py globals
Changes
Convert readme.md to readme.rst, move extra docs. [Stephen L Arnold]
Fixes
Fix included filename and link cleanup. [Stephen L Arnold]
Remove more py2 cruft from doctesting (py3.10 warnings) [Stephen L Arnold]
Update maintainer info and spec test cmd. [Stephen L Arnold]
update coverage value for delta/base, allow digits only
Use updated bandit action and workflow excludes (exclude test) [Stephen L Arnold]
also fix missing PR event check in coverage workflow
Use current org-level coverage workflow. [Stephen L Arnold]
increase fetch depth and update regex
updated action deps, relaxed run criteria
go back to “normal” tokens, remove permission hacks
still needs more job isolation => refactor for another day
Other
Use buildbot account. [Katelyn Gigante]
Use ACCESS_TOKEN secret rather than provided GITHUB_TOKEN. [Katelyn Gigante]
Should fix the coverage badge
v0.6.1 (2021-11-24)
Changes
Add shallow checkout for testing. [Stephen L Arnold]
Bump comment action to latest release, verify checkout depth. [Stephen L Arnold]
see: https://github.com/marocchino/sticky-pull-request-comment/issues/298 in upstream action repo
Fixes
Use workflow PR target and checkout params. [Stephen L Arnold]
Split coverage (checkout) job from PR comment job. [Stephen L Arnold]
Use correct tox env cmd for single platform/version. [Stephen L Arnold]
For older changes through v0.6.0 see the HISTORY.md file in the repository.