Symfony2: Assetic Twig Functions

In my post Symfony2: Using Assetic for Image Optimisation I looked at using Assetic for image optimisation. In that I looked at OptiPNG set up like this in the config:

and using a Twig template that looks like this:

In order to optimise a PNG file. It is possible however to achieve this with a much simpler Twig template by setting up a Twig function from the Assetic config. By adding the following config:

The Twig template can be changed to the following:

Note that we are no longer using the apply_to filter and instead explicitly specifying the optipng filter with the function call.

You can specify the output directory in the config in the following way:

The function name maps directly to the filter name so these must be the same for this to work. You can only use this to map using a single filter, so for more complex combining of files and use of multiple filters, as you may want to do for JavaScript and CSS files, this is not an appropriate solution. For images though, where you will usually only want to apply a single filter to a single file this is an excellent way of simplifying your Twig templates.