Package: minijinja
MiniJinja for Python: a powerful template engine for Rust and Pythonminijinja-pyis an experimental binding ofMiniJinjato Python.  It has somewhat
limited functionality compared to the Rust version.  These bindings usematurinandpyo3.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 packagefrom PyPI:$ pip install minijinjaBasic APIThe basic API is hidden behind theEnvironmentobject.  It behaves almost entirely
like inminijinjawith some Python specific changes.  For instance instead ofenv.set_debug(True)you useenv.debug = True.  Additionally instead of usingadd_templateor attaching asourceyou either pass a dictionary of templates
directly to the environment or aloaderfunction.fromminijinjaimportEnvironmentenv=Environment(templates={"template_name":"Template source"})To render a template you can use therender_templatemethod:result=env.render_template('template_name',var1="value 1",var2="value 2")print(result)PurposeMiniJinja 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 LoadingMiniJinja'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 callenv.reload()or
alternatively setenv.reload_before_rendertoTrue.defmy_loader(name):segments=[]forsegmentinname.split("/"):if"\\"insegmentorsegmentin(".",".."):returnNonesegments.append(segment)try:withopen(os.path.join(TEMPLATES,*segments))asf:returnf.read()except(IOError,OSError):passenv=Environment(loader=my_loader)env.reload_before_render=Trueprint(env.render_template("index.html"))Alternatively templates can manually be loaded and unloaded withenv.add_templateandenv.remove_template.Auto EscapingThe default behavior is to use auto escaping file files ending in.html.  You can
customize this behavior by overriding theauto_escape_callback:env=Environment(auto_escape_callback=lambdax:x.endswith((".html",".foo")))MiniJinja usesmarkupsafeif it's available
on the Python side.  It will honor__html__.FinalizersInstead 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 whenpass_stateis used) and can return a new value.
If the specialNotImplementedvalue 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 AccessFunctions passed to the environment such as filters or global functions can
optionally have the template state passed by using thepass_stateparameter.
This is similar topass_contextin Jinja2.  It can be used to look at the
name of the template or to look up variables in the context.fromminijinjaimportpass_state@pass_statedefmy_filter(state,value):returnstate.lookup("a_variable")+valueenv.add_filter("add_a_variable",my_filter)Runtime BehaviorMiniJinja uses it's own runtime model which is not matching the Python
runtime model.  As a result there are clear gaps in beahvior 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.Markupobject will appear as safe string in
MiniJinja.  This information can also flow back to Python again.SponsorIf you like the project and find it useful you canbecome a
sponsor.License and LinksDocumentationExamplesIssue TrackerMiniJinja PlaygroundLicense:Apache-2.0