Twig

A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, LaTeX, etc.).
It doesn’t have a specific extension, .html or .xml are just fine. A template contains variables or expressions, which get replaced with values when the template is evaluated, and tags, which control the logic of the template. Below is a minimal template that illustrates a few basics. We will cover further details later on:

<!DOCTYPE html>
<html>
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>
<h1>My Webpage</h1>
{{ a_variable }}
</body>
</html>

 

There are two kinds of delimiters: {% … %} and {{ … }}. The first one is used to execute statements such as for-loops, the latter prints the result of an expression to the template.

 

Variables
The application passes variables to the templates for manipulation in the template. Variables may have attributes or elements you can access, too. The visual representation of a variable depends heavily on the application providing it.
You can use a dot ( . ) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array), or the so-called “subscript” syntax ( [] ):

{{ foo.bar }}
{{ foo['bar'] }}

When the attribute contains special characters (like – that would be interpreted as the minus operator), use the attribute function instead to access the variable attribute:

If a variable or attribute does not exist, you will receive a null value when the strict_variables option is set to false; alternatively, if strict_variables is set, Twig will throw an error (see environment options).

 

Global Variables
The following variables are always available in templates:

  1. _self : references the current template name;
  2. _context : references the current context;
  3. _charset : references the current charset.

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'} %}

 

Looping in Twig

Fromsitepoint

 

<?php

require_once __DIR__.'/bootstrap.php';
// Create a product list

$products = [
    [
        'name'          => 'Notebook',
        'description'   => 'Core i7',
        'value'         =>  800.00,
        'date_register' => '2017-06-22',
    ],
    [
        'name'          => 'Mouse',
        'description'   => 'Razer',
        'value'         =>  125.00,
        'date_register' => '2017-10-25',
    ],
    [
        'name'          => 'Keyboard',
        'description'   => 'Mechanical Keyboard',
        'value'         =>  250.00,
        'date_register' => '2017-06-23',
    ],
];

// Render our view

echo $twig->render('index.html', ['products' => $products] );

Then, we use the render() method which accepts a template name (this is a file inside the template folder that we defined earlier) and the data that we want to pass to the template.

To complete our example, let’s go inside our /templates folder and create an index.html file. First, let’s take a look at the template itself.

<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Twig Example</title>
    </head>
    <body>
    <table border="1" style="width: 80%;">
        <thead>
            <tr>
                <td>Product</td>
                <td>Description</td>
                <td>Value</td>
                <td>Date</td>
            </tr>
        </thead>
        <tbody>
            {% for product in products %}
                <tr>
                    <td>{{ product.name }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.value }}</td>
                    <td>{{ product.date_register|date("m/d/Y") }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    </body>
</html>

In our example we’ve already seen how a loop is done using Twig. Basically, we use the for tag and assign an alias for each element in the specified array. In our case, we assigned the alias product for our products array. After that, we can access all the attributes in each array element by using the . operator. We use the endfor tag to indicate the end of our loop.

We can also loop through numbers or letters using the .. operator. Just like the following:

{% for number in 0..100 %}
     {{ number }}
{% endfor %}
or for letters:

{% for letter in 'a'..'z' %}
     {{ letter }}
{% endfor %}
{% for number in 0..100 %}
     {{ number }}
{% endfor %}
or for letters:

{% for letter in 'a'..'z' %}
     {{ letter }}
{% endfor %}

End of Sitepoint

Filter

We can use Filter to control what and which format information to be passed in our template. Filters are separated from the variable by a pipe symbol ( | ) and we can modify the variable using the filter. Multiple filters can be chained. The output of one filter is applied to the next.

Date and date_modify
The date filter formats a date to a given format. As we can see in our example:

<td>{{ student.date_register|date("m/d/Y") }}</td>

On top of the date filter, we can change the date with a modifier string using the date_modify filter. For example, if we wanted to add a day to our date we could use the following:

<td>{{ product.date_register|date_modify("+1 day")|date("m/d/Y") }}</td>