Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Coding Standards
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x, 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

Coding Standards

Note

The Twig CS fixer tool uses the coding standards described in this document to automatically fix your templates.

When writing Twig templates, we recommend you to follow these official coding standards:

  • Put exactly one space after the start of a delimiter ({{, {%, and {#) and before the end of a delimiter (}}, %}, and #}):

    1
    2
    3
    {{ user }}
    {# comment #}
    {% if user %}{% endif %}

    When using the whitespace control character, do not put any spaces between it and the delimiter:

    1
    2
    3
    {{- user -}}
    {#- comment -#}
    {%- if user -%}{%- endif -%}
  • Put exactly one space before and after the following operators: comparison operators (==, !=, <, >, >=, <=), math operators (+, -, /, *, %, //, **), logic operators (not, and, or), ~, is, in, and the ternary operator (?:):

    1
    2
    3
    {{ 1 + 2 }}
    {{ first_name ~ ' ' ~ last_name }}
    {{ is_correct ? true : false }}
  • Put exactly one space after the : sign in mappings and , in sequences and mappings:

    1
    2
    [1, 2, 3]
    {'name': 'Fabien'}
  • Do not put any spaces after an opening parenthesis and before a closing parenthesis in expressions:

    1
    {{ 1 + (2 * 3) }}
  • Do not put any spaces before and after string delimiters:

    1
    2
    {{ 'Twig' }}
    {{ "Twig" }}
  • Do not put any spaces before and after the following operators: |, ., .., []:

    1
    2
    3
    4
    {{ name|upper|lower }}
    {{ user.name }}
    {{ user[name] }}
    {% for i in 1..12 %}{% endfor %}
  • Do not put any spaces before and after the parenthesis used for filter and function calls:

    1
    2
    {{ name|default('Fabien') }}
    {{ range(1..10) }}
  • Do not put any spaces before and after the opening and the closing of sequences and mappings:

    1
    2
    [1, 2, 3]
    {'name': 'Fabien'}
  • Use snake case for all variable names (provided by the application and created in templates):

    1
    2
    {% set name = 'Fabien' %}
    {% set first_name = 'Fabien' %}
  • Use snake case for all function/filter/test names:

    1
    2
    {{ 'Fabien Potencier'|to_lower_case }}
    {{ generate_random_number() }}
  • Indent your code inside tags (use the same indentation as the one used for the target language of the rendered template):

    1
    2
    3
    4
    5
    {% block content %}
        {% if true %}
            true
        {% endif %}
    {% endblock %}
  • Use : instead of = to separate argument names and values:

    1
    {{ data|convert_encoding(from: 'iso-2022-jp', to: 'UTF-8') }}