How can you set a variable based on the session in the base branch template?

I want to attach a twig to an application that will need some session based data embedded in the database. For example, the current customer footer is displayed in the footer. It doesn't make sense for individual controllers to know about this, since it has nothing to do with them; but on the other hand they select and populate the view:   

class MyController 
{

    public function index()
    {
        $template = $this->twig->loadTemplate('myPageTemplate.html.twig');
        return $template->render($dataArray);
    }
}

      

Is there some well-formed way to push a data object to a branch before picking a view and making the base template available? Is there something you would do when starting Twig_Environment and passing it in?

+3


source to share


3 answers


Session variables must be set in the controller. As you can see in the docs , it would look something like this:

public function indexAction(Request $request)
{
    $session = $request->getSession();

    // store an attribute for reuse during a later user request
    $session->set('foo', 'bar');

    // get the attribute set by another controller in another request
    $foobar = $session->get('foobar');

    // use a default value if the attribute doesn't exist
    $filters = $session->get('filters', array());
}

      



These variables are then easily passed in when rendering the template with something like:

return $this->redirect($this->generateUrl('home', array('foobar' => $foobar)));

      

+1


source


If you don't want all of your controllers to deal with injecting these "global" variables, you can implement a base controller class that inherits all other controllers, and do the following internally:

public function render($view, array $parameters = array(), Response $response = null)
{
    if(!isset($parameters['timezone'])) {
         // fill the parameter with some value
        $parameters['timezone'] = $this->getSession()->get('timezone');
    }
    return parent::render($view, $parameters, $response);
}

      



This allows you to do "global" injection without giving up control entirely from your controllers.

Remember to make your base controller a Symfony \ Bundle \ FrameworkBundle \ Controller \ Controller extension.

+1


source


A better approach would be to add a Twig extension so you don't need to include anything in your controller. With an extension, you can either add a global as someone else suggested ( http://twig.sensiolabs.org/doc/advanced.html#globals ) or functions ( http://twig.sensiolabs.org/doc/advanced .html # functions ) which can then be used directly (eg {{user_timezone ()}}).

+1


source







All Articles