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 3.0.0)
STARTUP │ (Re)initialized boot script
DIRECTOR │ Launched worker 0
PHASE │ run
START │ runpy ./plan.py
SUCCESS │ runpy ./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 │ Stopping workers
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.
Try the Following¶
-
Change the values in
config.yaml
and 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()
.