Step: jinja¶
Renders requested Jinja2 template with document context and optionally other data.
Input¶
If not used as a first step, then the previous document is available from document variable.
Output¶
Results to a file of specified type (via content-type option) and file extension (via extension option).
Options¶
template= path to template file to be renderedcontent-type= MIME type of resulting fileextension= file extension for the produced file (without leading dot)
Optional:
jinja-ext= comma-separated list of Jinja2 extensions to be enabled (supported values:debug)extras= comma-separated list of related entities to query in addition to Document Context (possible values:submissions,project); values will be added toextrasattribute of the document contextpolicy.*= Jinja2 policies:policy.truncate.leeway,policy.urlize.rel,policy.urlize.target,policy.urlize.extra_schemes, andpolicy.json.dumps_kwargs.<name>
The i18n-dir, i18n-domain, and i18n-lang options were removed and are ignored, see Translations.
Template (Jinja2)¶
Variables¶
The following variables are set:
ctx= contains JSON-like plain Document Context (possibly withextrasattribute, if configured)secrets= dictionary of secret values, only if enabled by configuration filerequests= wrapper of requests module only if enabled by configuration filedatetime= Python datetime modulezoneinfo= Python zoneinfo modulejson= Python json modulerdflib= RDFLib module if installed
The requests wrapper allows only http and https URLs. Hosts resolving to private, loopback, or link-local addresses are rejected unless allowed by the security configuration of the document worker. TLS verification cannot be disabled, the timeout cannot be extended, and redirects are limited and checked. Credentials are dropped when a redirect points to another host.
Functions¶
The following functions are available as Jinja globals.
assets¶
The assets(file) function retrieves an Asset object from a template file or an uploaded questionnaire file. The file argument can be one of three types:
stringvalue with path to asset file within the template (relative from its root), e.g."assets/logo.png";ProjectFile object from Objectified Document Context, e.g. from reply to a File Question passing file from it simply as
reply.file;dictrepresenting a questionnaire file retrieved from regular Document Context, i.e. an item of thectx['questionnaire']['files']list.
As a result you get either Asset object as described below or None in case no such asset is found.
assets function with static template file¶{%- set asset = assets("assets/logo.png") -%}
{%- if asset and asset.is_image -%}
<img src="{{ asset.data_url }}" alt="Our logo" />
{%- endif -%}
assets function with Objectified Document Context¶{%- set dc = ctx|to_context_obj -%}
{# Get the file from the questionnaire files using the reply.file UUID #}
{%- set file = dc.questionnaire.files[reply.file.uuid] -%}
{%- set asset = assets(file) -%}
{%- if file and asset and asset.is_image -%}
<img src="{{ asset.data_url }}" alt="{{ asset.name }}" />
{%- elif file -%}
<p>Questionnaire file {{ file.name }} ({{ file.uuid }}) is not an image.</p>
{%- else -%}
<p>Questionnaire file does not exist.</p>
{%- endif -%}
assets function with Document Context¶{%- for ctxFile in ctx.questionnaire.files -%}
{%- set asset = assets(ctxFile) -%}
{%- if asset and asset.is_image -%}
<img src="{{ asset.data_url }}" alt="{{ asset.name }}" />
{%- elif asset -%}
<p>Questionnaire file {{ asset.name }} ({{ asset.uuid }}) is not an image.</p>
{%- else -%}
<p>Questionnaire file not found.</p>
{%- endif -%}
{%- endfor -%}
Every Asset object returned by assets() function has the following attributes:
uuid- UUID of the assetname- original name (file name)content_type- MIME typedata- data stored as bytesdata_base64- base64-encoded datadata_url- data URL (convenient for use in <img> tags)is_image- boolean flag indicating if the asset is an image
Filters¶
Within Jinja templates, you can use so-called filters. Basically, those are functions applied to a first argument using pipe | symbol.
Builtin Filters¶
There are several widely used builtin filters directly in Jinja.
Value Conversion¶
We provide several filters that can be used for conversion of values:
datetime_format= Formats timestampExample:
x.created_at|datetime_format("%d/%m/%y")Arguments:
iso_timestamp-datetimeor ISO 8601strfmt- datetime format passed to strftimetz(optional) - timezone name (e.g."UTC","Europe/Prague") for formatting the timestamp; if not provided, UTC is used
of_alphabet= Converts integer to charactersExample:
x|of_alphabetIt prints
a(for 0) tozand then continues withaa,ab, etc.Arguments:
n- integer >= 0, usually some index
roman= Converts integer to Roman numeralExample:
x|romanArguments:
n- integer >= 0, usually some index
markdown= Converts markdown to HTMLExample:
x|markdownThe result is sanitized by default because Markdown may contain raw HTML. Scripting, embedded content, stylesheets, and URLs with unexpected schemes are removed. Use
x|markdown(sanitize=false)only for content fully controlled by the document template, never for user input.Arguments:
md_text- string containing Markdown syntaxsanitize(optional) - whether the resulting HTML is sanitized (default:True)
bytesize_format= Formats number of bytesExample:
file.size|bytesize_format
dot= Ends sentence if not already endedExample:
"This sentence has no end"|dotArguments:
text
extract= Extracts values from object by having keysExample:
entities.questions|extract([uuid1, uuid2, uuid3])Arguments:
obj- object for getting values (typicallydict)keys- list of keys to retrieve
Special¶
These filters are more complex and add various support to template development.
to_context_obj= Converts plain context to well-defined objectsThis filter is used for easier transition and might be removed in the future.
Arguments:
ctx- plain JSON-like document context
jinja2= Renders a string as a Jinja templateExample:
"Hello {{ name }}"|jinja2({"name": "Alice"})Arguments:
template_str- string with the templatevariables(optional) - dictionary with variablesfail_safe(optional) - return an empty string instead of failing (default:False)
error= Stops generating the document with an error messageExample:
"This template needs a project"|errorArguments:
message- error messagetitle(optional) - error title
Tests¶
Within Jinja templates, you can use so-called tests. Basically, those are helpers usable in conditions after is keyword:
{% if loop.index is divisibleby 3 %}
{# ... #}
{% endif %}
Builtin Tests¶
There are several widely used builtin tests directly in Jinja.
Custom Tests¶
not_empty= Checks if size of a collection is higher than 0Example:
items is not_empty
of_type= Checks if an object is instance of a certain type / classThe name must be a string; however, it is case-insensitive. It also checks all superclasses.
Example:
parent is of_type "ListQuestion"
Replies Extraction¶
You can use the extract_replies filter to extract replies easily while using KM annotations. Version 1 stays the default, prefer version 2 in new templates.
With default configuration, you should use json.key annotation on chapters and questions and json.value annotation on answers and choices to easily extract replies from the document context:
{%- set dc = ctx|to_context_obj -%}
{%- set object = dc|extract_replies({'version': '2'}) -%}
{{ object.dataset.title._value }}
The given configuration replaces the respective values of the defaults:
{%- set dc = ctx|to_context_obj -%}
{%- set config = {
'variant': 'simple',
'version': '1',
'annotations': {
'key': 'json.key',
'value': 'json.value',
},
'options': {
'include_reply_objects': False,
},
} -%}
{%- set object = dc|extract_replies(config) -%}
{{ object|tojson(indent=2) }}
The result is a dictionary keyed by the json.key annotations, nested as follows:
A chapter with a key is an object under that key. The questions of a chapter without a key are in the result itself.
The follow-up questions of the selected answer are in the object of the options question. If the options question has no key, they are in the object that holds it.
List and multi-choice questions are lists, and the item questions of a list are in the object of each item.
Questions without a key are left out. A list question without a key leaves out all its item questions (a warning is logged).
Two questions with the same key in one object overwrite each other (a warning is logged).
The objects have the following fields, which use underscored names to avoid conflicts with the annotations:
Question |
Version 1 |
Version 2 adds |
|---|---|---|
value |
|
|
integration |
|
|
options |
|
|
multi-choice |
List of |
|
list |
List of |
|
item select |
|
|
file |
|
|
With the include_reply_objects option, each object has _reply. For list and multi-choice questions, each item and each choice has it.
In version 1:
An unanswered question is
None(lists and multi-choice questions are[]) and the follow-ups of unselected answers are absent, so a path through an unanswered question fails.json.valueis converted loosely:trueandfalsein any case to booleans, and anything Python’sint()orfloat()accepts to a number (007becomes7).
In version 2:
Every annotated question is present. Unanswered ones are objects with
_valueset toNone(lists and multi-choice questions are[]), and the follow-ups of unselected answers are added in the same way, so any path along the knowledge model is safe.json.valueis converted only if it is exactlytrue,false, or a plain integer without leading zeros. Everything else stays a string.
Translations¶
A document template can be translated without releasing a new version. The language of the template declares the language of its source strings, and each translation is uploaded as a document template locale (a PO file). Language is then a parameter of document generation, so one format can produce documents in several languages.
Mark strings using the Jinja2 i18n extension, which is always enabled:
{# TRANSLATORS: heading of the first chapter #}
<h1>{% trans %}Introduction{% endtrans %}</h1>
{{ _('Data Management Plan') }}
{{ ngettext('%(num)d answer', '%(num)d answers', answers|length) }}
{{ pgettext('menu', 'Open') }}
{% trans %} blocks are always trimmed, so re-indenting a template does not orphan its translations. Use {% trans notrimmed %} where the whitespace matters, for example in <pre> or a plain-text format.
The document worker generates a POT file after a document template is released or imported. We can also create it locally using dsw-tdk pot. Only files with the .j2, .jinja, .jinja2, or .jnj extension are scanned. DSW reads the locale code from the Language header of the uploaded PO file, so that header must be filled in correctly. If a locale cannot be downloaded or is corrupt, document generation fails.
To migrate a template, remove i18n from jinja-ext because it is always enabled, and drop the removed i18n-dir, i18n-domain and i18n-lang options. Merge the per-language formats into one format per output type and set the template’s language. Release the template, download the POT file, and upload the existing catalogs as locales.
Notes¶
All paths (e.g. for
importorextendsin Jinja2 templates are relative from the template root, i.e. directory withtemplate.json).The
do,loopcontrols, andi18nJinja2 extensions are always enabled.Jinja can render templates with any extension. For translation extraction, use one of the extensions listed under Translations.
The document context is provided in
ctxvariable, other variables, filters, and tests are documented in other documents.
Example¶
{
"name" : "jinja",
"options" : {
"template" : "src/default.html.j2",
"content-type" : "text/html",
"extension" : "html"
}
}
Rendering permissions and resources¶
HTTP requests require explicit enablement for the template in the worker configuration. Only HTTP and HTTPS URLs are allowed. The worker’s resource policy controls access to private, loopback and link-local addresses and checks redirect destinations. Templates cannot override TLS verification or the configured timeout, proxies and hooks; credentials are removed on cross-host redirects.
The markdown filter sanitizes generated HTML by default. Its optional sanitize=false argument is only suitable for content controlled by the template author; keep sanitization enabled for project answers.
Validate output with long answers, escaped user content, translations and uploaded files in every supported format.
Source-aware templates¶
A template offered for both projects and editor previews must handle either source:
{% set x = ctx|to_context_obj %}
<h1>{{ x.project.name if x.project else x.km_editor.name }}</h1>
Custom rendering extensions use the dsw_templating_plugins entry point. Extensions using the earlier dsw.document_worker imports or dsw_document_worker_plugins entry point need updating for the shared renderer.