Symfony2: Session Global variable in PHP template

12,807

In twig: {{ app.session.varname }}

In PHP: echo $app->getSession()->get('uid');

Share:
12,807
Nadjib Mami
Author by

Nadjib Mami

Data Engineer @ Deutsche Post DHL Group PhD Student @ Bonn University Work topics: Data Management, Big Data, Linked Data

Updated on June 21, 2022

Comments

  • Nadjib Mami
    Nadjib Mami almost 2 years

    Symfony doc says:

    During each request, Symfony2 will set a global template variable app in both Twig and PHP template engines by default. The app variable is a GlobalVariables instance which will give you access to some application specific variables automatically:
    app.security - The security context.
    app.user - The current user object.
    app.request - The request object.
    app.session - The session object.
    app.environment - The current environment (dev, prod, etc).
    app.debug - True if in debug mode. False otherwise.

    Examples:
    In twig: {{ app.request.method }}
    In PHP: echo $app->getRequest()->getMethod() In twig: {{ app.user.username }}
    But for the session object:
    In twig: {{ app.session.varname }}
    In PHP: // I don't know, do you know how to call it?

    I've tried: $session = $app->getSession('uid'); but when I try to store it to a database it tells me:

    Catchable Fatal Error: Object of class Symfony\Component\HttpFoundation\Session could not be converted to string in C:\wamp\www...

    There's a lack of resources when it comes to PHP templates, but in my case I can't switch for some reasons.

    The question in other words, what is the equivalent in PHP templating of:
    {{ app.session.varname }}?

  • Nadjib Mami
    Nadjib Mami about 12 years
    Are you sure that works either in a page.html.php template? It gives me this err: Notice: Undefined property: Symfony\Bundle\FrameworkBundle\Templating\Helper\SessionHelp‌​er::$uid in C:\wamp\www\... I'm already using your code in the Default Controller for each controller and render the session value, the thing I'm trying to avoid by my question here, I need to use a global variable as the Symfony2 docs says above.
  • Nadjib Mami
    Nadjib Mami about 12 years
    Hey are you kinda mocking me? :) Great guy, that did it, thanks a ton for your answer.
  • Cerad
    Cerad about 12 years
    No mocking intended. I had your question commented out and positioned to make it clear as to which problem was being addresses. Then @Daniel Ribereiro went in and edited stuff. No idea why but it messed the intent up.
  • Aysennoussi
    Aysennoussi over 10 years
    You're using .varname in twig and then get('uid') in PHP?