Home » Software, Coding & Hosting » Hosting & Websites » Twig Tutorials » Twig template syntax

Twig template syntax

    There are three syntaxes in Twig template: {{ }} The “output something” syntax, {% %} The “do something” syntax and {# #} comment syntax

    Twig syntaxes 

    In previous articles we give an Introduction to Twig template engine then we describe how to Setup Twig template engine and in this article we will discuss the Twig template syntaxes and Twig tags

    Say something syntax in Twig template: {{ … }}

    The double curly brace ( {{ ) is the first Twig syntax that we should learn. We use it to display the value of a variable or function.

    Variables in a template are anything you pass to the template. it can be the article’s title, phone number, or something else. If we want to output any variable; we just put in a double curly brace 

    {{ title }}
    {{ foo.bar }}

    Please note that we use the dot (.) to access the elements of an array or the properties of an object.

    Read more about The “Say Something” Syntax on symfonycasts.com

    To learn more about the variables in Twig, you can visit the variables page on the official site.

    The comment syntax in Twig template: {# … #}

    Sometimes we need to write some comments and without rendering them in the output. to do this we use the comment syntax 

    {# This is comment #}

    Do something syntax in Twig template: {% … %}

    The curly-percent ({%) is the other syntax, We use it to request Twig to do some this such as check a condition or step over a loop

    Codes in Twig

    Twig contains 5 kinds of code; tags, functions, filters, tests, and operators, sometimes the same keyword resent in two different groups with different uses. 

    Tags

    Twig tags are control structures that control the flow of the templates. We use tags inside to do something syntax. close each tag in twig with “end” followed by the tag name. ex endif, endfor, and endapply.

    “if” tag and conditional outputs

    Let’s say that we have students and a list of exam marks and we want to display a greeting for smart students. I the other hand, we need to check the student’s mark before displaying the greeting 

    {# Each condition starts with "if" tag within do something syntax #}
    {% if mark > 90 %}
    Hello smart student {{ name }}
    {# Each condition end with endif #}
    {% endif %}
    {# note that endif is a single word #}

    In the first line, Twig checks the student’s mark represented by the variable mark. If it is over 90, it continues to the next line, showing the welcome message, then we use the “endif” to close the condition.

    Also, the if tag in Twig can check if a variable has a value. Suppose we have a variable named agent and we want to display a text when it contains any text.

    {% if agent %}
    We have an agent in your area
    Our agent: {{ agent }}
    {% endif %}

    Another example let’s say we have a price and we want to if the price equal zero 

    {% if price == 0 %}
    This product is free
    {% elseif price > 10 %}
    This product is cheap,
    {% else %}
    You have to pay {{ price }}
    {% endif %}

    Please note that we use the == operator to check for equality. And that we use “elseif” to add other conditions. Finally, the “else” keyword checks if we cannot pass all previous conditions.

    Note that every if tag must be closed by the endif keyword.

    For more information on using the if tag, see the Twig documentation.

    Loops and the repetition of something

    If our field or variable is an array. We can use the “for” tag to loop with elements one by one, we can execute a command or display some information for each of those elements using for as in the following example:

    {% for name in names_list %}
    Hello: {{ name }}
    {% endfor %}

    where names_list is the name of the array and “name” is the name given to each element of the array.

    In the next line, the commands between “for” and “endfor” are executed on all the elements of the array. Thus, in our previous example, a welcome message appears for each of the names contained in the array. The last line is to close the loop and inform the template engine that it should follow the rest of the template instructions normally. Anything that comes after {% endfor %} does not belong to the loop.

    Each “for” tag must end with {% endfor %} and please note that endfor is one word, not two.

    Here is a sample Twig template to display a list of products with their price:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Products</title>
    </head>
    <body>
    <h1>Products</h1>
    {# This is a comment and will not render #}
    {% for product in products %}
    Product name: {{ product.name }}<br>
    {% if product.price == 0 %}
    Free
    {% else %}
    Procust price {{ product.price }}
    {% endif %}
    {% endfor %}
    </body>
    </html>

    The “set” tag and internal variables

    We can assign a value to a variable using a “set” tag

    {% set student = 'Ziad' %}
    Hello {{ student }}
    {# output: Hello Ziad #}

    We can use numbers, text, and array for values

    {% set age = 20 %}
    {% set colors = ['red', yellow'] %}

    There is another method to use the “set” tag

    {% set student %}
    Ziad
    {% endset %}

    The “include” tag

    The include tag is used to insert the contents of another template within the current template, allowing us to split files or reuse parts of them. The contents of any plain text file can also be included, not just a twig file.

    Let’s say, for example, that we want to write web pages and we want to reduce the effort by avoiding writing an Html header on each page, then we create a file called “header.twig“.

    {# file name: header.twig #}
    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>{{ title }}</title>
    </head>
    <body>
    <h1>{{ title }}</h1

    After that, we can write another page like this

    {% include ‘header.twig’ %}
    My 1st article
    </body>
    </html>

    We can also pass a value of the variable in the header file so that we change the title of the web page:

    {% include 'header.twig' with {'title': 'My 1st page'} %}
    My 1st article
    </body>
    </html>

    We can also store the contents of the file in a variable, say we write a general description of the company in a text file and then want to use that description as the value of an internal variable in a Twig template:

    {% set description %}
    {% include ‘description.txt’ %}
    {% endset %}
    {# or #}
    {% set description = include('description.txt') %}

    What are the filters in Twig?

    Twig filters process the data before displaying it or assigning it to an internal variable. The data itself is not affected and remains as it is. We use filters in say something syntax {{ }}. To use the filter we put after the name of the variable ( | ) then we write the filter name. Look at the following example:

    {% set student = 'Ziad' %}
    Welcome {{ student|upper }}
    Hello {{ student }}
    {# outputs:
       Welcome ZIAD
       Hello Ziad #}

    In other words, we invoke any filter in Twig; it uses the value of the variable as the 1st parameter to a specific producer and then shows us the result.

    {{ 'my first car'|capitalize }}
    {# outputs 'My first car' #}

    Format filter

    The format filter formats a given string by replacing the placeholders %s.

    {{ "Hello student %s"|format('Ziad') }}
    {# output: Hello student Ziad #}

    Escape Filter and safe output

    It is one of the most important filters, as it is used to get rid of any invalid data that may cause problems in the display, and we always prefer to use it with text variables. We can shorten the escape filter to “e”:

    {# escape for Html safety #}
    <div>{{ description|e }}</div>

    We can also write it as:

    {# escape for Html safety #}
    <div>{{ description|escape }}</div>

    The escape filter escapes a string using strategies that depend on the context. By default, it uses the HTML escaping strategy. We can pass an argument to the previous filter to specify a type that fits where the variable will appear. Example:

    {# escape for JS safety #}
    <script>
        function getDescription() {
            return {{ description|e('js') }};
        }
    </script>
    {# escape for CSS safety #}
    <style>
        {{ mystyles|e('css') }}
    </style>

    For more information about this filter, you can visit the filters documentation, list of filters

    Functions

    Twig functions are a set of codes that generate content or perform a task. We can call the function multiple times.
    We call functions by their name followed by parentheses (()) and may have arguments within those parentheses to pass information to the function.
    For example, range returns an array containing integers between two numbers:

    {% for i in range(0, 3) %}
        {{ i }},
    {% endfor %}
    {# outputs 0, 1, 2, 3, #}

    When calling the previous function, we pass two arguments to it, the first argument is the beginning of the range, the second is the end of the range, we can pass a 3rd the third argument as a step or the difference between two numbers in the range and it is optional.

    The “block” tag and the “block” function

    In Twig we can have a function that has the same name used for the tag. The word block in Twig may refer to the block tag, and it may also refer to the block function. We can distinguish easily the two cases through the following example:

    <html>
    <head>
    <title>
    {% block title %}
        Hello Twig.
    {% endblock %}
    </title>
    </head>
    <body>
    <h1>{{ block('title') }}</h1>
    </body>
    </html>

    We note that the tag is within the do something syntax {% %} and is used to identify the block and specify its contents, while we use the “block” function inside say something syntax {{ }}. The block function returns the contents of a block that was previously defined.

    The “date” filter and the “date” function

    The date filter changes the date format when the value of a variable is shown in the given syntax

    {{ birth|date("m/d/Y") }

    On the other hand, the date function returns to the current date when called without arguments:

    {{ date() }}
    {#show current date#}

    You can pass an argument to the date function, and the value of the argument can be a text expression for the date, for example, the text “2022/01/01” is converted to the corresponding date. It can also be a difference in date from the current date:

    {{ date('2022/01/01') }}
    {#Returns the exact date 01/01/2022#}
    {{ date('-2days') }}
    {# Returns the current date minus two days #}

    We can pass two arguments where the second argument contains the time zone:

    {{ date('-2days', 'Europe/Paris') }}
    {% if post.date > date('-30days') %}
        This is a new post
    {% endif %}

    The difference between a filter and a function

    Filters in Twig have the following characteristics:

    • We use filters for data processing
    • The filter always returns the value
    • The value returned by the filter is always text
    • The candidate takes one or more mediators
    • We write the first argument before the (|) and placed, example:
      {{ student|upper }}
    • When we need to pass a second argument, we added parentheses after the filter name, and put the argument between them
      {{ description|escape(‘html’) }}
    • Please note that the first argument is the same variable that comes before the (|).

    As for the functions:

    • We intend functions to return a value that is not normally associated with data
    • The value returned by the function can be text, a number, a date, or an array
    • Functions in Twig always return a value, which differs from the definition of functions in programming languages
    • Functions can take no arguments and can take one or more arguments
    • Even when the function does not take any argument, parentheses follow it
      {{ date() }}
    • When a function needs argument, we pass to it in parentheses:
    {% set list = range(1, 6) %}

    Tests in Twig

    The is operator performs tests.

    {% if line is odd %}
    .......
    {% endif %}

    We used it with the is operator to check that the variable fulfills a specified condition. The pre-defined tests in Twig are: defined, divisible by, even, iterable, odd, same as
    For more information about the exams, you can refer to see the official documentation

    Finally

    In this article, we have talked about the Twig components of tags, filters, functions, and tests, which are the key components of Twig template.

    Discussions

    You can share your feedback on this post via the flowing facebook post

    End