如何动态调用树枝过滤器

use*_*963 1 symfony twig

我需要使用特定于每种数据类型的过滤器呈现未知类型的数据:

渲染的结构看起来像:

array(
    "value"  => "value-to-render",
    "filter" => "filter-to-apply",
)

{% for item in items %}
    {{ item.value|item.filter|raw}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

所以我的问题是:如何使用item.filter作为值的过滤器?

Vit*_*ian 6

您必须编写过滤器,它将通过将名称传递给过滤器来调用过滤器.

如何最初写你扩展你可以在这里阅读.

假设您已经创建了扩展,那么您已经定义了自定义函数(例如,customFilter).

//YourTwigFilterExtension.php

public function getFunctions()
{
    return array(
        ...
        'custom_filter' => new \Twig_Function_Method($this, 'customFilter'),
    );
}
Run Code Online (Sandbox Code Playgroud)

然后,您必须定义此功能

public function customFilter($context, $filterName)
{
    // handle parameters here, by calling the 
    // appropriate filter and pass $context there
}
Run Code Online (Sandbox Code Playgroud)

在这种操作之后,你将能够在Twig中调用:

{% for item in items %}
    {{ custom_filter(item.value, item.filter)|raw  }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

或者,如果您已将过滤器定义为过滤器(而非功能):

{% for item in items %}
    {{ item.value|custom_filter(item.filter)|raw  }}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)