How to apply a filter whose name is stored in a variable

Basically, I'm looking for the equivalent of a function filter attribute()for objects and arrays. I want to be able to apply a filter whose name is stored in a variable.

{# 
    This works and is really useful 
    prints object.someVar 
#}
{% set varName = 'someVar' %}
{{ attribute(object,varName) }} 

{#
    The function "filter" does not exist
#}
{% set filterName = 'somefilter' %}
{{ filter(object,filterName) }} 
+3
source share
1 answer

To achieve this, you must expand your TwigFilter.

How to write you an extension from the beginning, you can read here .

Assuming you created the extension, you defined your function, say applyFilter.

//YourTwigFilterExtension.php

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

Then you must define this function

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

After these manipulations, you can call Twig:

{{ apply_filter(object, 'filterName') }} 

Greetings;)

+1
source

All Articles