Skip to research

Functions - In Twig Templates Drupal 8

Temps de lecture
Environ 1 minutes
Étiquettes

attach_library($library)

#

Attaches an asset library to the template.

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

 

Create new Attribute objects using the create_attribute() function inside a Twig template. These objects can then be manipulated just like other Attribute objects coming into the Twig template.

Introduced in 8.3.x

See change record: https://www.drupal.org/node/2818293

{% set my_attribute = create_attribute() %}
{%
  set my_classes = [
    'kittens',
    'llamas',
    'puppies',
  ]
%}
<div{{ my_attribute.addClass(my_classes).addAttribute('id', 'myUniqueId') }}>
  {{ content }}
</div>

<div{{ create_attribute({'class': ['region', 'region--header']}) }}>
  {{ content }}
</div>

 

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

 

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

 

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': 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.

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>