Using templates in Symfony framework. (Lesson 7. Twig)

Using templates in Symfony framework can be done in several ways. First, you can use PHP templates. But the preferred option is to use the Twig template engine (by default). Twig is a compiling open-source template engine written in PHP. It produces PHP/HTML code as output. Besides being very functional, Twig is also very fast.

So, first of all, it's important to understand some key features. Twig extends HTML by introducing three directives:

{{ ... }} - output something - a variable's value, the result of a function call, etc.

{% ... %} - template logic. Here you can have loops, conditions, and other structures.

{# ... #} - comments.

Let's look at the first two directives in more detail.

The first directive is straightforward: it outputs the value of a variable or an expression:

{{ title }}
Or with an array:
{{ content['sidebar'] }}
The second directive is more interesting. =)

Here's an example of using conditions:

{% if title is defined %}
  <h1>{{ title }}</h1>
{% endif %}
Loops:
{% for user in users %}
  {{ user.username }}
{% endfor %}
Twig has some built-in functions: range, cycle, constant, random, attribute, block, parent, dump, date.

It's convenient to use filters: date, format, replace, url_encode, json_encode, title, capitalize, upper, lower, striptags, join, reverse, length, sort, merge, default, keys, escape, e

For example, the following code will output text in uppercase:

{{"some text" | upper}}
You can also include external files:
{% include 'root/page.html' %}
But all of this is not as impressive (since it's quite easy to achieve with PHP) as Twig template inheritance.

In Twig, you can create elements, blocks:

{% block content %}
  <h1>Some text</h1> 
{% endblock %}

{% block other_content %} <h1>Some other text </h1> {% endblock %}

You can create a child template like this:
{% extends '::base.html.twig' %}
{% block content %}
  <h1>Inherited text</h1> 
{% endblock %}
This way, the block in the inherited template will be replaced. If you need to add to the block or access the value of the parent element, you can use the parent() function. For example:
{% extends '::base.html.twig' %}
{% block content %}
  parent()
  <h1>Inherited text</h1> 
{% endblock %}
That's pretty much it when it comes to the features of Twig that are necessary to get started.

Let's look at some aspects of the interaction between Twig and the Symfony framework.

As you should know from Lesson 3, templates are stored in src/Bundle_name/Resources/view by default. When working with templates, the addressing (which is important, for example, when using the inheritance mechanism) is as follows: bundle:controller:template. For example:

{% extends 'NameMyBundle:Default:basic_template.html.twig' %}
In the next lesson, we will learn how to include CSS, JS, images, and other external resources.