我想从我的Twig扩展(过滤器,函数…)访问Twig模板参数,而不显式传递它。
我总是需要一个"displayPreferences"变量在我所有的分支扩展,为了改变显示和转换值的方式。
可以将此变量作为模板参数传递,并将其作为我运行的每个Twig过滤器/函数的参数传递,但这会使模板难以阅读。
这样的东西会很好:
/**
* 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
}
}
你可以定义一个上下文感知过滤器:
如果您想要访问过滤器中的当前上下文,请设置Needs_context选项设置为true;将当前上下文传递为筛选器调用的第一个参数(或第二个参数)Needs_environment也设置为true):
传递的上下文包括模板中定义的变量。
因此更改过滤器的定义,添加所需的need_context参数:
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_escape和preserves_safety选项。
另外,如果你看一下twig的函数代码,它会显示'needs_context'是一个可用的选项。
下面是一个函数的例子,如果在函数调用期间提供,则接受传递的值,如果没有,则使用上下文变量(模板变量)的值:
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))
);
}
另一个在处理上下文时对我有帮助的快速提示:如果你想查看上下文中存在哪些变量,以便在你的twig函数或过滤器中引用,只需在模板中引用twig的转储函数{{ dump() }}
。