Skip to content

Using Twig functions & filters

Koen edited this page Aug 1, 2019 · 3 revisions

Since we're using Twig to render our templates, we can't simply add PHP to our templates to modify data or content. We'll need to resort to Twig filters and functions.

Using and adding custom functions

Custom Twig functions can be found in Grrr\Twig\Functions. New functions should usually be added there, unless they're really specific for a class (eg. a post type). An example:

{{ svg('cross')|raw }}

{#
<svg aria-hidden="true" role="presentation" focusable="false" data-icon="cross"> 
    <use xlink:href="http://localhost.example.com/app/themes/
        theme/assets/build/images/icons.svg#cross"/> 
</svg>
#}

Using and adding custom filters

Custom Twig filters can be found in Grrr\Twig\Filters. New filters should be added there. An example:

{{ title|slugify }}

{#
i-am-the-title
#}

Default functions/filters

Twig has some default filters and functions out of the box. View the documentation to get an overview.

Timber also has some more WordPress-oriented filters and functions. View the documentation to get an overview. Note that some classes have helper classes with filters as well.

Calling PHP functions

Note that it's possible to call native PHP functions from your Twig template by using the function function, but usually this is not recommended:

{{ function('php_function') }}
You can’t perform that action at this time.