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:

assetic:
    filters:
        optipng:
            bin: /path/to/optipng

and using a Twig template that looks like this:

{% image output="/images/test.png"
    '@LimeThinkingSpringBundle/Resources/images/test.png'
%}
    <img src="{{ asset_url }}" alt="The alt text" />
{% endimage %}

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:

assetic:
    filters:
        optipng:
            bin: /path/to/optipng
            apply_to: "\.png$"
    twig:
        functions:
            optipng: ~

The Twig template can be changed to the following:

<img src="{{ optipng('@LimeThinkingSpringBundle/Resources/images/test.png') }}" 
     alt="The alt text" 
/>

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:

assetic:
    filters:
        optipng:
            bin: /path/to/optipng
            apply_to: "\.png$"
    twig:
        functions:
            optipng: { output: images/*.png }

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.