Symfony2 global variables in TWIG

Featured Image © personalfx@sxc.hu

Except well documented TWIG functions like: path(),  asset(), … and custom variables you pass into view from controller when rendering some TWIG template, Symfony2 provides an easy way to access some ‘global’ variables inside TWIG templates without explicitly sending those to the view from controller.

Let me write some example:

Global variable app is start point to get some extra information inside TWIG templates.

With ‘app’ variable, we can access various objects data;

Public methods are available from following objects using app variable:

Symfony\Component\HttpKernel\Kernel
Symfony\Component\HttpFoundation\Request
Symfony\Component\Security\Core\SecurityContext
Symfony\Component\HttpFoundation\Session
Symfony\Component\Security\Core\Authentication\Token\TokenInterface::getUser

For example:

{# ... #}

{{app.kernel.cachedir}}
{{app.kernel.logdir}}
{{app.kernel.rootdir}}
 
{{app.request.basepath}}
{{app.request.baseurl}}
{{app.request.uri}}
 
{{app.security.token.user}}
 
{{app.session.locale}}
 
{# ... #}

I will now let you search more in those classes for getter functions that could be called and used in twig that way. Cheers 🙂


3 comments

  1. Seems like app.kernel was removed from the global variables (using Symfony 2.0.11). Maybe because it let you access the service container which I think is considered very bad behaviour in a Twig template.

  2. Nice one, for example with app.request.pathinfo you will always know which page is currently being viewed. Very useful if you want to test the current page from the template.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <blockquote cite=""> <code> <del datetime=""> <em> <s> <strike> <strong>. You may use following syntax for source code: <pre><code>$current = "Inchoo";</code></pre>.