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

Twig (in Symfony) : access template parameters from twig extensions

我想从我的 Twig 扩展(过滤器、函数...)访问 Twig 模板参数而不显式传递它。

我的所有 twig 扩展中总是需要一个 "displayPreferences" 变量,以便更改显示和转换值的方式。

可以将此变量作为模板参数传递,并将其作为参数传递给每个 Twig 过滤器/函数 I 运行,但这会使模板难以阅读。

这样的东西会很棒:

/**
 * 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
    }
}

你可以定义一个Context-aware Filters:

If you want to access the current context in your filter, set the needs_context option to true; Twig will pass the current context as the first argument to the filter call (or the second one if needs_environment is also set to 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
    }
}

除了能够定义上下文感知过滤器,让您按照已接受的答案中的说明引用模板变量,您还可以定义上下文感知函数。 twig documentation on functions 提到了这个:

Functions support the same features as filters, except for the pre_escape and preserves_safety options.

此外,如果您查看 twig's code for functions,它会显示 '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 function {{ dump() }} 在你的模板中。