An experimental Python binding of the Rust MiniJinja template engine.
Project description
minijinja-py
is an experimental binding of
MiniJinja to Python. It has somewhat
limited functionality compared to the Rust version. These bindings use
maturin and pyo3.
You might want to use MiniJinja instead of Jinja2 when the full feature set of Jinja2 is not required and you want to have the same rendering experience of a data set between Rust and Python.
With these bindings MiniJinja can render some Python objects and values that are passed to templates, but there are clear limitations with regards to what can be done.
To install MiniJinja for Python you can fetch the package from PyPI:
$ pip install minijinja
Basic API
The basic API is hidden behind the Environment
object. It behaves almost entirely
like in minijinja
with some Python specific changes. For instance instead of
env.set_debug(True)
you use env.debug = True
. Additionally instead of using
add_template
or attaching a source
you either pass a dictionary of templates
directly to the environment or a loader
function.
from minijinja import Environment
env = Environment(templates={
"template_name": "Template source"
})
To render a template you can use the render_template
method:
result = env.render_template('template_name', var1="value 1", var2="value 2")
print(result)
Purpose
MiniJinja attempts a certain level of compatibility with Jinja2, but it does not try to achieve this at all costs. As a result you will notice that quite a few templates will refuse to render with MiniJinja despite the fact that they probably look quite innocent. It is however possible to write templates that render to the same results for both Jinja2 and MiniJinja. This raises the question why you might want to use MiniJinja.
The main benefit would be to achieve the exact same results in both Rust and Python. Additionally MiniJinja has a stronger sandbox than Jinja2 and might perform ever so slightly better in some situations. However you should be aware that due to the marshalling that needs to happen in either direction there is a certain amount of loss of information.
Dynamic Template Loading
MiniJinja's Python bindings inherit the underlying behavior of how MiniJinja loads
templates. Templates are loaded on first use and then cached. The templates are
loaded via a loader. To trigger a reload you can call env.reload()
or
alternatively set env.reload_before_render
to True
.
def my_loader(name):
segments = []
for segment in name.split("/"):
if "\\" in segment or segment in (".", ".."):
return None
segments.append(segment)
try:
with open(os.path.join(TEMPLATES, *segments)) as f:
return f.read()
except (IOError, OSError):
pass
env = Environment(loader=my_loader)
env.reload_before_render = True
print(env.render_template("index.html"))
Alternatively templates can manually be loaded and unloaded with env.add_template
and env.remove_template
.
Auto Escaping
The default behavior is to use auto escaping file files ending in .html
. You can
customize this behavior by overriding the auto_escape_callback
:
env = Environment(auto_escape_callback=lambda x: x.endswith((".html", ".foo")))
MiniJinja uses markupsafe if it's available
on the Python side. It will honor __html__
.
Finalizers
Instead of custom formatters like in MiniJinja, you can define a finalizer instead
which is similar to how it works in Jinja2. It's passed a value (or optional also
the state as first argument when pass_state
is used) and can return a new value.
If the special NotImplemented
value is returned, the original value is rendered
without any modification:
from minijinja import Environment
def finalizer(value):
if value is None:
return ""
return NotImplemented
env = Environment(finalizer=finalizer)
assert env.render_str("{{ none }}") == ""
State Access
Functions passed to the environment such as filters or global functions can
optionally have the template state passed by using the pass_state
parameter.
This is similar to pass_context
in Jinja2. It can be used to look at the
name of the template or to look up variables in the context.
from minijinja import pass_state
@pass_state
def my_filter(state, value):
return state.lookup("a_variable") + value
env.add_filter("add_a_variable", my_filter)
Runtime Behavior
MiniJinja uses it's own runtime model which is not matching the Python
runtime model. As a result there are clear gaps in behavior between the
two and only limited effort is made to bridge them. For instance you will
be able to call some methods of types, but for instance builtins such as
dicts and lists do not expose their methods on the MiniJinja side. This
means that it's very intentional that if you pass a dictionary to MiniJinja,
the Python .items()
method is unavailable.
Here is what this means for some basic types:
- Python dictionaries and lists (as well as other objects that behave as sequences) appear in the MiniJinja side as native lists. They do not expose any specific other behavior and when they move back to the Python side they will appear as basic lists. Specifically this means that a tuple (which does not exist in MiniJinja) when moving from Python to MiniJinja turns into a list and will remain a list when it moves back.
- Python objects are represented in MiniJinja similarly to dicts, but they retain all
their meaningful Python APIs. This means they stringify via
__str__
and they allow the MiniJinja code to call their non-underscored methods. Note that there is no extra security layer in use at the moment so take care of what you pass there. - MiniJinja's python binding understand what
__html__
is when it exists on a string subclass. This means that amarkupsafe.Markup
object will appear as safe string in MiniJinja. This information can also flow back to Python again.
Sponsor
If you like the project and find it useful you can become a sponsor.
License and Links
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distributions
Hashes for minijinja-1.0.13-cp38-abi3-win_amd64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 897ef698f4bc6325c1d4db4a32fb25646ea6fdec75dbc24e4213c7863eaed935 |
|
MD5 | 5d0111e2eabe1cdbbcea6776e5e1b017 |
|
BLAKE2b-256 | 3804cc22e98c9870269d64abb4a0c2b69fe8ffb078b459218ec869f29d89ffe9 |
Hashes for minijinja-1.0.13-cp38-abi3-win32.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 44d3bbd96ca3a5960175ac34370bc2017eaa27f6b080dda630c42b23bc974017 |
|
MD5 | 961f5a68c9986300400ce5bf3d7988aa |
|
BLAKE2b-256 | 0c8a04868340d0ae5d1f3a2d9526c2bf41f0e3af5b2328868e4fdfb33f29fff9 |
Hashes for minijinja-1.0.13-cp38-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 59eb006b928d0ff87a2890283d67c4f01273f845850fb6c60f30fefca17ace51 |
|
MD5 | 40457d9b5c3cd2f86dc40b0529826067 |
|
BLAKE2b-256 | cbed0fba4cdd1dc84735bc078ddc2e7da793fd6c8dadd1e69cea431602cac55e |
Hashes for minijinja-1.0.13-cp38-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | effcfb90a855bf5e849cd2ef560ae8e37961e09ff4b62b7853c911cbd3629afe |
|
MD5 | 8828b13c7ad602d15bbf6091556eb653 |
|
BLAKE2b-256 | 55ce521a7f695e343b13c7e01c1f0dd0831fcaf0b3e27b9e92cf5e5d45942d7e |
Hashes for minijinja-1.0.13-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 9daaa3f01522b7fb83283411e6e82e6cf65623e84584487ee3aeae70e758a321 |
|
MD5 | b8cbdc94ec6da495e9175ca49f9f34f2 |
|
BLAKE2b-256 | f74e54c6e9cb532934eeb0650413230575975a66ef41df57da25e7748e69149b |
Hashes for minijinja-1.0.13-cp38-abi3-manylinux_2_5_i686.manylinux1_i686.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 99260c9c9a2a7c1849e26a49498a1937d4e25dad6123b06b11d6e8822bf3cccb |
|
MD5 | 344cdd29f483727b66fbcfad3d794857 |
|
BLAKE2b-256 | 391268e91f3b9642cee3bb1bfa0dce0054955f541e36d8282d877dcf9e552d2e |
Hashes for minijinja-1.0.13-cp38-abi3-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 26f9bd5abe88d5a3dff158b4cf8e655b9f2f6f27127a58b3791e41d12f1b9c60 |
|
MD5 | 32dec8b73e32f37459b21b9ec589fdb7 |
|
BLAKE2b-256 | a36d2fd0d085a454bf0b1987f4b6fc2d1251c2de4aa0aecd87b90ce747b51a2a |