如何动态调用树枝过滤器

编程入门 行业动态 更新时间:2024-10-27 18:29:23
本文介绍了如何动态调用树枝过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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 %}

更多推荐

如何动态调用树枝过滤器

本文发布于:2023-11-15 05:53:46,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591731.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   树枝   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!