Tutorial by Examples

In Twig templates variables can be accessed using double curly braces notation {{ variableName }}. Basic example of greeting user <!DOCTYPE html> <html> <body> <span>Hello {{ name }}</span> </body> </html> Accessing array elements Twig as ...
Variables can be modified using filters. To apply filter to variable follow variable name with pipe | and filter name: {{ variable|filterName }} For example to display variable value in uppercase use construct. {{ variable|upper }} Filters can be parametrized. Filter parameters are passed in...
Parts of template can be displayed conditionally. If statement is used for this purpose. It's similar to if statement in programing languages. Contents of block are executed/displayed if an expression evaluates to true. {% if enabled == false %} Disabled {% endif %} Disabled will be displ...
For loops can be really useful in TWIG, allowing the creation of data-dynamic web pages. Say we create a simple array of numbers: {% set array = "3,1,2" %} We can then iterate over the array and print out whatever we want. Any data within the array block will be outputted in relation ...
The ternary operator (?:) Support for the extended ternary operator was added in Twig 1.12.0. {{ foo ? 'yes' : 'no' }} Evaluates: if foo echo yes else echo no {{ foo ?: 'no' }} or {{ foo ? foo : 'no' }} Evaluates: if foo echo it, else echo no {{ foo ? 'yes' }} or {{ f...
To remove whitespace (spaces, tabs, newlines…) between HTML tags use spaceless tag: {% spaceless %} <div> <span>foo bar </span> </div> {% endspaceless %} {# produces output <div><strong>foo bar </strong></div> #} If you need ...

Page 1 of 1