d0001
d0001

Reputation: 2190

Filter or function in TWIG?

When should some functionality be created as a filter instead of a function and vice versa?

user | function

vs

function(user)

Someone pointed out the documentation, however it does not explain when to use which. It does say this:

Functions support the same features as filters, except for the pre_escape and preserves_safety options.

What is the point of twig support function if they behave just like a filter?

Upvotes: 22

Views: 6823

Answers (2)

Jan Klan
Jan Klan

Reputation: 884

I'd like to add that functions could make more sense where the code you want to execute has no input you can supply from within the Twig template.

Say you wanted to show a warning if you detect an unsupported browser based on the User Agent. Assuming you don't have the variable holding the User Agent at hand, you could use a TwigFunction like this:

{% if not supportedBrowser() %} ... {% endif%}

If you did have the User Agent available in any variable in the current Twig scope, you could use a filter and call it like this:

{% if not app.request.headers.get('user-agent')|supportedBrowser %} ... {% endif %}

The above would work if your Twig template ran in a Symfony application.


With all that said, if you had the User Agent in a local variable, filter may not be the best approach. You could write a Twig Test and use it like this:

{% if app.request.headers.get('user-agent') is not supportedBrowser %} ... {% endif %}

I know this veers away from the original question, but I think it is important to be aware of a "C" option, when considering "A or B".

As a personal opinion, using a Twig Test in this particular context is easier to read/understand as it converts the underlying logic into plain language.

Upvotes: 3

sf_tristanb
sf_tristanb

Reputation: 8855

A filter is a way to transform the displayed data. For example if you want to display the content of a variable L1K3 Th1s, you'll have to write a filter (example : {{ username|l33t }})

A function is used when you need to compute things to render the result. For example, the {{ dump(username) }} function which will call internally the var_dump php function.

Usually you write a function when you need to do heavier things than just simply transform the display of a content in a simple way.

Upvotes: 35

Related Questions