Php 细枝(Symfony):从细枝扩展访问模板参数
我想从我的细枝扩展(过滤器、函数…)访问细枝模板参数,而不显式传递它 在我的所有细枝扩展中,我总是需要一个“displayPreferences”变量,以便更改显示和转换值的方式 可以将此变量作为模板参数传递,并将其作为我运行的每个细枝过滤器/函数的参数传递,但这会使模板难以读取 像这样的东西太好了:Php 细枝(Symfony):从细枝扩展访问模板参数,php,symfony,templates,twig,Php,Symfony,Templates,Twig,我想从我的细枝扩展(过滤器、函数…)访问细枝模板参数,而不显式传递它 在我的所有细枝扩展中,我总是需要一个“displayPreferences”变量,以便更改显示和转换值的方式 可以将此变量作为模板参数传递,并将其作为我运行的每个细枝过滤器/函数的参数传递,但这会使模板难以读取 像这样的东西太好了: /** * Twig filter (render a date using the user defined format) * * @param Date $date */ publi
/**
* Twig filter (render a date using the user defined format)
*
* @param Date $date
*/
public function renderUserDate ($date) {
// Somehow, get a template parameter, without receiving it as argument
$renderPreference = $this->accessTemplateParameter('displayPreferences');
switch ($renderPreference['dateFormat']) {
// Do something
}
}
您可以定义一个:
如果要访问筛选器中的当前上下文,请设置
需要将上下文选项设置为true;Twig将当前上下文作为
筛选器调用的第一个参数(或第二个参数,如果
需要(环境也设置为true):
传递的上下文包括模板中定义的变量
因此,更改过滤器的定义,添加所需的need_上下文参数:
public function getFilters()
{
return array(
new \Twig_SimpleFilter('price', array($this, 'renderUserDate', ,array('needs_context' => true)),
);
}
然后使用以下示例:
/**
* Twig filter (render a date using the user defined format)
*
* @param array $context: injected by twig
* @param Date $date
*/
public function renderUserDate ($context, $date) {
// defined in the template
$renderPreference = $context['displayPreferences'];
switch ($renderPreference['dateFormat']) {
// Do something
}
}
除了能够定义上下文感知过滤器,允许您引用接受答案中提到的模板变量外,还可以定义上下文感知函数。报告提到: 函数支持与过滤器相同的功能,但 pre_逃生并保留_安全选项 此外,如果你看一看,它会显示“需要上下文”作为可用选项之一 下面是一个函数示例,如果在函数调用期间提供了传递的值,则该函数将采用传递的值;如果不是,则使用上下文变量(模板变量)中的值: 在使用上下文时帮助我的另一个快速提示:如果您想查看上下文中存在哪些变量,以便在您的twig函数或筛选器中引用,只需在模板中引用twig的
{{dump()}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction('photobox', function($context, $page = false) {
$page = $page ? $page : $context['page'];
return $this->app['helper.theme']->photobox($page);
}, array('needs_context' => true))
);
}