Functions - In Twig Templates

Last updated on
9 October 2017

Twig provides a number of handy functions that can be used directly within Templates.

List of Twig Functions

Drupal core adds a handful of custom functions that are Drupal specific. These are defined in the TwigExtension class.

You can also define your own custom Twig functions in a custom module (but not in a theme). To find an example for how to do this, see this example in core/modules/system/tests/modules/twig_extension_test/src/TwigExtension/TestExtension.php.

url($name, $parameters, $options)

Generate an absolute URL given a route name and parameters:

<a href="{{ url('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>

Generate an absolute URL to the current url:

<a href="{{ url('<current>') }}">{{ 'Reload'|t }}</a>

Generate an absolute URL to the front page:

<a href="{{ url('<front>') }}">{{ 'Home'|t }}</a>

path($name, $parameters, $options)

Generates a [relative] URL path given a route name and parameters.

{# Link to frontpage view. #}
<a href="{{ path('view.frontpage.page_1') }}">{{ 'View all content'|t }}</a>

{# Link to user entity/profile page. #}
<a href="{{ path('entity.user.canonical', {'user':}) }}">{{ 'View user profile'|t }}</a>

{# Link to node page. #}
<a href="{{ path('entity.node.canonical', {'node':}) }}">{{ 'View node page'|t }}</a>

The url and path function are defined in close parallel to those found in \Symfony\Bridge\Twig\Extension\RoutingExtension.

link($text, $url, $attributes)

This helper function accepts as first parameter the text and as second parameter the url

{{ link(item.title, item.url, { 'class':['foo', 'bar', 'baz']} ) }}


This helper function accepts a relative path from the root and creates a relative URI path to the file.

{{ file_url(node.field_example_image.entity.uri.value) }}


Attaches an asset library to the template.

{{ attach_library('classy/node') }}