Twig(在Symfony中):从twig扩展访问模板参数

Con*_*501 4 php templates symfony twig

我想从我的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
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*teo 8

您可以定义上下文感知过滤器:

如果要访问过滤器中的当前上下文,请将needs_context选项设置为true; Twig将当前上下文作为过滤器调用的第一个参数传递(如果needs_environment也设置为true,则传递第二个参数):

传递的上下文包括模板中定义的变量.

因此,更改过滤器的定义,添加所需的need_context参数:

public function getFilters()
    {
        return array(
            new \Twig_SimpleFilter('price', array($this, 'renderUserDate', ,array('needs_context' => true)),
        );
    }
Run Code Online (Sandbox Code Playgroud)

然后使用例如:

/**
 * 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
    }
}
Run Code Online (Sandbox Code Playgroud)