πTemplates
Overview
A template serves as a blueprint for text generation. Its flexibility allows it to produce content in any text-based format. Within a template, you'll find two primary components:
Variables or Expressions: These elements get substituted with actual values during the template's evaluation.
Tags: They guide the logic behind the template's rendering.
To provide a foundational understanding, consider the template below, demonstrating essential features:
List of individuals:
{% for person in people %}
- {{ person.name }} {{ person.last_name }}
{% endfor %}
{{ a_variable }}
Templates use two distinctive delimiters:
- {% ... %}
: Executes statements, such as loops or conditionals.
- {{ ... }}
: Displays the resulting value of an encapsulated expression.
We'll delve deeper into the nuances and capabilities of templates in subsequent sections.
Variables
The application passes variables to the templates for manipulation in the template. Variables may have attributes or elements you can access, too.
Use a dot (.) to access attributes of a variable:
{{ foo.bar }}
Implementation
It also supports a specific syntax for accessing items using foo['bar']
instead of foo.bar
.
If a variable or attribute does not exist, you will receive a null value.
Setting Variables
You can assign values to variables inside code blocks. Assignments use the set
tag:
{% set foo = 'foo' %}
{% set foo = [1, 2] %}
{% set foo = {'foo': 'bar'} %}
Filters
Filters offer a method to modify variables within templates. They're separated from the variable using a pipe symbol (|
). It's feasible to chain multiple filters together, applying the output of one as the input for the subsequent filter.
Consider this example that strips any HTML tags from a name and then converts it to title-case:
{{ name|striptags|title }}
Filters accepting parameters use parentheses to enclose these arguments. The illustration below showcases how elements of a list can be joined using commas:
{{ list|join(', ') }}
For applying a filter over a chunk of text, encase it with the apply
tag:
{% apply upper %}
This text becomes uppercase
{% endapply %}
For an in-depth exploration of built-in filters, navigate to the filters page.
Functions
Functions within templates are tools that generate specific content. To invoke a function, use its name followed by parentheses (()
). These functions can also accept arguments.
Take, for instance, the range
function. It returns a list containing a sequence of integers:
{% for i in range(0, 3) %}
{{ i }},
{% endfor %}
For a comprehensive overview of built-in functions, refer to the functions page.
Named Arguments
Named Arguments in Templates
Templates provide support for named arguments across functions, filters, and tests.
Here's how you can utilize named arguments within a range
function:
{% for i in range(low=1, high=10, step=2) %}
{{ i }},
{% endfor %}
Employing named arguments makes templates clearer about the significance of values passed as arguments. Consider these encoding conversion examples:
{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}
Vs.
{{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }}
Additionally, named arguments empower you to bypass certain arguments, retaining their default values. In this date example:
{# Here, the first argument represents the date format. If null is passed, it defaults to the global date format #}
{{ "now"|date(null, "Europe/Paris") }}
You can also exclusively employ a named argument for clarity:
{{ "now"|date(timezone="Europe/Paris") }}
It's possible to mix both positional and named arguments in a single invocation. Ensure positional arguments precede named ones:
{{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }}
Control Structure
Control structures play a pivotal role in directing the program flow, encompassing conditionals (like if/elseif/else
), for-loops
, and constructs such as blocks. Typically, these structures are encapsulated within {% ... %}
delimiters.
For instance, to render a list of users from a users
variable, the for
tag is employed:
Users:
{% for user in users %}
- {{ user }}
{% endfor %}
The if
tag facilitates testing expressions:
{% if users|length > 0 %}
{% for user in users %}
- {{ user }}
{% endfor %}
{% endif %}
For a comprehensive understanding of built-in tags, navigate to the tags page.
Comments
In templates, the comment syntax {# ... #}
offers a method to comment out portions of lines. This proves especially useful for debugging, or for leaving informative notes to fellow template designers or for future reference:
{# note: disabled template because we no longer use this
{% for user in users %}
...
{% endfor %}
#}
Escaping
At times, there might be a need for the template engine to overlook certain sections that it would usually treat as variables or blocks. For instance, if you're want to display {{
as a raw string in the template without initiating a variable, you'd need a workaround.
A straightforward method to achieve this is by outputting the variable delimiter ({{
) through a variable expression:
{{ '{{' }}
For lengthier sections, marking a block as verbatim
is more suitable.
Macros
Macros can be likened to functions in standard programming languages. They serve a valuable purpose in facilitating the reuse of fragments, promoting the DRY (Don't Repeat Yourself) principle. Detailed insights on macros can be found in the macro tag documentation.
Expressions
Expressions allow for operations, comparisons, and evaluations within templates. They provide functionality ranging from simple math and string manipulations to intricate logical and comparison checks.
For a comprehensive list of supported expressions, consult the expressions documentation.
Last updated