Functions - In Twig Templates

Last updated on
8 February 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)

Generates an absolute URL given a route name and parameters.

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

Generates an absolute URL to the current url.

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

Generates 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') }}">{{ 'View all content'|t }}</a>

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

{# Link to node page. #}
<a href="{{ path('entity.node.canonical', {'node': node.id}) }}">{{ '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

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

file_url($uri)

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) }}

attach_library($library)

Attaches an asset library to the template.

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