[Symfony 2] Twig – Global Variables

Schon mal gefragt, welche globalen Variablen in der Twig-Extension eines Symfony 2 (Standard Distri)-Projektes zur Verfügung stehen?
Schaut man sich die Klasse GlobalVariables im Namespace Symfony\Bundle\FrameworkBundle\Templating an (diese Klasse ist Teil des Framework-Bundles, d.h., Gleiches gilt ebenfalls für PHP als Template-Maschine), wird einiges klarer. Weiter unten eine Liste der Assessoren, die die Klasse bereitstellt:

    Symfony\Component\Security\Core\SecurityContext|void         getSecurity()
    Symfony\Component\Security\Core\User\(Advanced)UserInterface getUser()
    Symfony\Component\HttpFoundation\Request|void                getRequest()
    Symfony\Component\HttpFoundation\Session|void                getSession()
    string                                                       getEnvironment()
    bool                                                         getDebug()

In Twig liegt der Container im “app”-Namespace, “Übersetzt” nach Twig heißt das ganze also:

    app.security
    app.user
    app.request
    app.session
    app.environment
    app.debug

Viel Spaß beim Templates-Bauen ;)

7 Replies to “[Symfony 2] Twig – Global Variables”

  1. The master of the internet told me to do so, but never reported back since then :(

    Perhaps i decide to translate the article in the near future, in the meantime i suggest to investigate the contents of the class Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables which should make things clear.

  2. In the time you commented back to the first response, you could have translated this post :(

    Thanks for pointing out the GlobalVariables.php file though!

  3. Once you find the GlobalVariables.php all you have to do is make functions inside that file (with the same naming conventions) and Symfony will Automagically allow the use of those functions inside of Twig.

    Example:

    public function getHttp()
    {
    if ($request = $this->getRequest()) {
    return $request->getHttpHost();
    }
    }

    use {{ app.http }} in your Twig

  4. Indeed. The above article is not about how to inject new globals but how to identify existing ones – written in a time where there was only little documentation about twig integration into symfony (performed by twig bundle/twig bridge).

    So please consider this post as outdated and refer to the official symfony templating documentation and related cookbook articles.

    For myself i would always prefer writing a twig extension in favor of depositing globals into the “twig”-section of config.yml.

Comments are closed.