Rendering Files with Jinja¶
Jinja is a popular templating engine for Python. Given a template file and a set of variables, Jinja renders the template, i.e. it inserts the variables. It allows you to create dynamic content by embedding Python-like expressions in your templates.
This section will show you how to use render_jinja().
Internally, it uses StepUp’s loadns() function to load variables,
then uses Jinja2 to render a template, and finally writes the result to an output file.
Example¶
Example source files: docs/advanced_topics/render_jinja/
Create a file plan.py with the following contents:
#!/usr/bin/env python3
from stepup.core.api import render_jinja, static
static("email_template.txt", "config.yaml")
render_jinja("email_template.txt", "config.yaml", "email.txt")
Prepare a template file email_template.txt with the following contents:
Finally, create the config.yaml configuration file with the following contents:
Make the plan executable and run StepUp:
You should see the following output:
DIRECTOR │ Listening on /tmp/stepup-########/director (StepUp Core 3.2.3.post54)
STARTUP │ (Re)initialized boot script
PHASE │ build
START │ ./plan.py
SUCCESS │ ./plan.py
START │ render-jinja email_template.txt config.yaml email.txt
SUCCESS │ render-jinja email_template.txt config.yaml email.txt
DIRECTOR │ Trying to delete 0 outdated output(s)
DIRECTOR │ See you!
The result is a rendered email template with the values from the configuration file,
written to email.txt:
Supported Delimiters¶
With the mode option, render_jinja()
supports the following delimiters for Jinja templates:
- The default Jinja delimiters (
mode="plain"):{{ variable }}{% statement %}{# comment #}
- The LaTeX-friendly delimiters (
mode="latex"):<< variable >><% statement %><# comment #>
The default is mode="auto", which sets the delimiters automatically based on the file extension
(mode="latex" for .tex templates and mode="plain" otherwise).
Use mode="latex" when the template is LaTeX source:
its <<, <% and <# delimiters do not clash with LaTeX’s own {, } and % characters,
which the default Jinja delimiters would.
For all other templates, mode="plain" (the standard Jinja delimiters) is the natural choice.
Try the Following¶
-
Change the values in
config.yamland run the plan again. The email template should be rendered with the new values. -
You can also separate the loading of variables and the rendering of the template. The
render_jinja()also accepts a dictionary of variables instead of (or in addition to) filenames with variables. Use this to load the variables withloadns()first, then pass the loaded variables torender_jinja().