如何在树枝基础模板中设置基于会话的变量?
作者:互联网
我想将细枝插入需要将一些基于会话的数据并入基础的应用程序中.例如,客户端的当前时区显示在页脚中.各个控制器对此一无所知,因为这与他们无关.但另一方面,他们选择并填充视图:
class MyController
{
public function index()
{
$template = $this->twig->loadTemplate('myPageTemplate.html.twig');
return $template->render($dataArray);
}
}
在选择视图之前,是否有某种格式正确的方法可将数据对象传递到树枝,并使该对象可用于基本模板?在启动Twig_Environment并将其传递时,您会做些什么?
解决方法:
会话变量需要在控制器中设置.可以看到in the docs,它看起来像这样:
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());
}
然后,在渲染具有以下内容的模板时,可以轻松传递这些变量:
return $this->redirect($this->generateUrl('home', array('foobar' => $foobar)));
标签:symfony,twig,template-inheritance,php 来源: https://codeday.me/bug/20191121/2051449.html