Twig syntax

Twig templates have their own syntax. We present here only the most important rules necessary for a basic understanding of Twig.

The Twig syntax is well documented. As a starting point the section Twig for template designers is recommended.

Identifier

In Twig, the following three identifiers are used.

Comments

A comment can be single-line or multi-line. Everything between {# and #} is commented out.

Example

Single-line comment

{# my comment #}

It is also possible to comment out parts of the code.

Example

Multiline comment with commented out code

{# commented out code - the code will not be executed
{{ variable }}
#}

Output of variables

You can output a variable with {{ name_of_variable }}.

Example

Output of a variable

<p>output: {{ name_of_variable }} </p>

Commands and control structures

In the broadest sense, this refers to everything that is connected to controlling the output of variables. Only the most common ones are presented here, which are also often used in Contao templates.

If query

When you want certain output to occur only when a condition is met, you use the If query.

Example

If query

{% if my_variable %}
<p>The variable has the following content:</p>
<p>{{ my_variable }}</p>
{% endif %}

For loop

A For loop is used to execute code repeatedly. A typical application example is the output of the contents of an array.

Example

For loop

<ul>
    {% for item in items %}
        <li>{{ item }}</li>
    {% endfor %}
</ul>

Filter

Filters are applied to variables. They specify how a variable should be processed.

Example

filter

{{name of variable|name_of_filter }}

Filters in Twig are extremely powerful and versatile. Twig brings many Filters out of the box. Developers can also create their own create their own filters.
If you are interested in creating your own filters please have a look at the Developer Documentation.

Do you want to try something? You can use Twig fiddle for that.