In Twig it’s not possible to call filters based on a variable per default. I’ve created therefore a small Symfony bundle that provides a new Twig filter apply_filter which does exactly that: Calls filter based on a variable. Useful when you want to give your users a way to format something and therefore the filters comes from the database.

Download

You can download and install this Twig apply_filter extension here:

github.com/marcj/twig-apply_filter-bundle

Or via packagist:

packagist.org/packages/marcj/twig-apply_filter-bundle

Example

{{ set filters = 'upper|nl2br' }}

{{ value|apply_filter(filters) }}

{{ value|apply_filter("default('abc')|json_encode") }}

A filter for e.g. a News system, where the title filter is stored in the database:

{% for item in newsItems %}
    <h2>{{ item.title|apply_filter(databaseSettings.newsFilter) }}</h2>
{% endfor %}