user1063963 user1063963 - 1 year ago 171
Twig Question

How to call a twig filter dynamically

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

the rendered structures looks like:

"value" => "value-to-render",
"filter" => "filter-to-apply",

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

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

Answer Source

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.

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


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

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 %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download