Interaction between Twig and Symfony framework. Global variables (Lesson 8.2)

We are already familiar with the twig templating engine, know how to write markup on it and include external files (assets). Now we just need to consider some aspects of interaction in Symfony framework.

First, in order to display a template, we need to call the render method in the controller:

// src/Acme/ArticleBundle/Controller/ArticleController.php
class ArticleController extends Controller
  {
     public function recentArticlesAction($max = 3)
       {
        $articles = ...;
     return $this->render(
        'AcmeArticleBundle:Article:recentList.html.twig',
        array('articles' => $articles)
       );
      }
}
The array (second argument) sets the list of variables available from the template.

In addition, there is the ability to work with global (as for php scripts) variables.

Available global variables:

  • app.security - The security context.
  • app.user - User object.
  • app.request - Request object.
  • app.session - Session object.
  • app.environment - Current environment (dev, prod, etc.).
  • app.debug - True if debug build. False if production.
Global variables in Twig can have very useful applications.

For example, to find out from which script the template render (or its fragment) was called, it is not necessary to pass its name. It is enough to refer to the global value (global variable or method) (in this case, we will get the route from which the template was called):

 {% if app.request.attributes.get('_route') == "route_name" %}
...
{% endif %}
We can also get the parameters:
 {{ app.request.attributes.get('_route_params') }}
We can also easily get user parameters, access session variables, etc.

In addition to the "standard" global variables, there is the possibility to add custom ones. To do this, you need to modify the configuration file:

# app/config/config.yml
twig:
    # ...
    globals:
        ga_tracking: UA-xxxxx-x
Now this variable will be available in all templates:
<p>The google tracking code is: {{ ga_tracking }}</p>