{{ row[col.key] | col.filter }}
我在 col.filter 变量中有过滤器。我尝试创建以下链接中提到的评估过滤器,https://github.com/fabpot/Twig-extensions/pull/53/files 也尝试 https://github.com/marcj/twig-apply_filter-bundle 或调用类似
{{ row[col.key] | eval(col.filter) }}
或
{{ eval(row[col.key] , col.filter) }}
但它不起作用。
该问题的演示在这里,
https://github.com/vishalmelmatti/twig_dynamic_filter
好吧,这有点毛茸茸的,但是使用 template_from_string + 包含方法怎么样?有点丑,可能很贵,但至少它应该可以工作。
概念验证:
{% set col, row = { key: 'x', filter: 'raw' }, { x: '<b>one</b>', y: '<b>two</b>' } %}
{{ include(template_from_string('{{ row[col.key]|' ~ col.filter ~ ' }}')) }}
。将输出:一个
虽然这...
{% set col, row = { key: 'x', filter: 'escape' }, { x: '<b>one</b>', y: '<b>two</b>' } %}
...
。将输出:一
此时
您不能这样做,但我建议您创建自己的 twig 方法或过滤器,将要应用的过滤器作为参数。
我建议您使用这个捆绑包或从中获得灵感:https://github.com/marcj/twig-apply_filter-bundle
如 IRC 所述,您可以采用另一种方法,并使用Format
接口将格式应用于您的元素:
这里有一个简单的 POC https://gist.github.com/Lumbendil/d94109e91ceab7fae7e7
这是解决方案:
https://github.com/marcj/twig-apply_filter-bundle
这是一个Symfony捆绑包,可以准确地提供您所需要的东西。您也可以在没有symfony的情况下使用它。