Twig is a modern templating language for PHP. It is both developer and designer-friendly language as it incorporates PHP Principals and functionality required by templating environments. This article talks about the common use-cases you need to code using Twig templates. Learn more about Twig, here

Twig Basic Syntax

Displaying Variables

Displaying a variable is very simple. The code snippet below displays the value of var

{{var}}

The use of double-curly braces around a variable displays its value.

Implementing Conditional Statements

Using if-statement, you can evaluate if a condition is true or not. Execute line A if Condition X is fulfilled else execute line B. 

{% if a == b %}

…..

…..

{% endif %}

Implementing Loops

To traverse lists or arrays Twig has a provision of for loops. The code snippet below shows how to implement a for loop

Let's say “projects” is an array of objects where each object has properties named “id” and “name”. We can iterate on this array and access the properties of each object like this:

[
   {% for project in projects %}
      {
         "id": "{{ project.id }}",
         "value": "{{ project.name }}"
      }
         {% if not loop.last %} , {% endif %}
   {% endfor %}
]

This for loop generates a new JSON array of objects by slightly renaming the properties. loop.last checks whether the object is the last one in the array. It is TRUE if the object is the last object in the array. 

Implementing Filter

Applying filters are really straightforward. They transform the values on their left-hand side to another representation, depends upon the filter you apply. The value and the filter are separated by a | symbol. You can apply multiple filters to a single value too. The code snippet below shows how to apply a filter to some data object. 

{{my_data | json_encode }} (1)
{{article.last_updated | date (“m/d/y”)}} (2)

(1) Returns the JSON representation of the value. 

(2) Changes the date on the L.H.S to the format mentioned in the filter.  

Besides the features and functionalities mentioned above, Twig has a lot more. We hope you found this article helpful.

Happy Integrating!

Did this answer your question?