如何动态调用树枝过滤器 [英] How to call a twig filter dynamically

查看:34
本文介绍了如何动态调用树枝过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to render data with unknown type with filters that specific on each data type:

渲染的结构看起来像:

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

{% for item in items %}
    {{ item.value|item.filter|raw}}
{% endfor %}

所以我的问题是:我怎样才能让 twig 使用 item.filter 作为值的过滤器?

So My Question is: How can I get twig to use item.filter as a filter on the value?

推荐答案

你必须编写你的过滤器,它会通过传递名称来调用过滤器.

You have to write your filter, which will call filters by passing name to it.

最初如何编写扩展,您可以在此处阅读.

How to initially write you Extension you can read here.

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

Assuming that you have created you extension, you have define your custom function, (e.g., customFilter).

//YourTwigFilterExtension.php

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

那么,你必须定义这个函数

Then, you have to define this function

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

在此操作之后,您将能够在 Twig 中调用:

After this manipulations you'll be able to call in Twig:

{% for item in items %}
    {{ custom_filter(item.value, item.filter)|raw  }}
{% endfor %}

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

Or, if you've defined your filter as filter (not as function):

{% for item in items %}
    {{ item.value|custom_filter(item.filter)|raw  }}
{% endfor %}

这篇关于如何动态调用树枝过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆