Functions and filters to get you started with Twig Tweak in Drupal 8 (with examples)Akshay Devadiga23 Jun, 2020

Twig tweak module is a huge time saver for Drupal developers working with advanced twig templates. It offers several useful functions and filters that can ease the developer’s job. Developers can also write well formatted code which is more comprehensible. I highly recommend usage of the Twig tweak module in Drupal 8 for quick and easy Drupal development. What’s more, Twig tweak is also supported in Drupal 9!

Twig tweak

How to Install the Twig Tweak Module

You can either download and install the module from Drupal.org or from composer. Once you download and extract the file, place inside your project directory. You can also choose to use composer to download with the following command – 

composer require drupal/twig_tweak

Go to Extend and enable the module. You can even use drush to enable the module.

Implementing Twig Tweak Functions and Filters in Drupal 8

Views and views results

To render the views in twig template, we can use the twig tweak snippet as below.

Syntax 
 {{ drupal_view(views_name, display_id, args...) }}
 {{ drupal_view_result(views_name, display_id) }}
 
 Arguments

 views_name : Machine name of the views.
 display_id: Machine name of the current display.
 args : Optional arguments for filters. 


Examples

  • {{ drupal_view('who_s_new', 'block_1') }}  This will place the who’s new views block_1 in a template.
  • {{ drupal_view('who_s_new', 'block_1', arg_1, arg_2) }} Extra arguments can be passed if the contextual filters are added can be used with passing arguments.
  • {% set view = drupal_view_result('related', 'block_1')|length %}
    {% if view > 0 %}
    {{ drupal_view('related', 'block_1') }}

{% endif %} In this code the view is displayed only if the view has results in a template.

Blocks

To place the plugin blocks in template, we can use the twig tweak snippet as below.

Syntax
 {{ drupal_block('plugin_id', {label: 'Example'|t, some_setting: 'example'}) }} 
 
Arguments

 
  plugin_id : Plugin id of the blocks can be found in class annotations of the block.
 options : Second parameter is optional for providing  the configurations for the blocks.


Example 
{{ drupal_block('system_breadcrumb_block') }} to place the breadcrumbs block in template.

Region

To render the region contents from default or specific theme.

Syntax {{ drupal_region(region_name, theme_name) }}
 Arguments

 region_name :  Machine name of the region can be found at info.yml   file.

 theme_name : Optional theme name to render the region content of   specific theme other than default.


Example
{{ drupal_region('sidebar_first', 'bartik') }} to place the sidebar first contents of the bartik theme in a template.

Entity and Entity form

To render the available entity and entity form in twig template, we can use the snippet as below.

Syntax

 {{ drupal_entity(entity_type, id, view_mode, language, access_check) }}

 {{ drupal_entity_form(entity_type, id, form_mode, values, access_check ) }}

Arguments 

 entity_type : Type of an entity i.e node, block, block_content, webform,     paragraphs etc.
 Id: Id of an entity. 
 view_mode: To view the entity by its viewmode available.
 language:  To specify language if not it will take default site language. 
 access_check: To check the access of block default value is true.
 form_mode: To view the entity form by its formmode available. 
 values: Array of property values defaults to [].

Examples

  • {{ drupal_entity('block_content', 1) }}  to display the content block whose id is equal to 1 in a twig template.
  • {{ drupal_entity('node', 123, 'teaser') }} to display the node teaser data of entity whose id is equal to 123.
  • {{ drupal_entity_form('node', 1) }} to display node edit entity form in a template.
  • {{ drupal_entity_form('node', values={type: 'article'}) }} to display node add form of article type.

Field

To display the available field value of any entity in twig template or to get field value, use the following twig tweak snippet.

Syntax {{ drupal_field(field_name, entity_type, id, view_mode, language,access_check) }}
Arguments

 field_name:  Machine name of the field.
 entity_type : Type of an entity i.e node, block, block_content, webform,   paragraphs etc. 
 Id: Id of an entity.
 view_mode: To view the entity by is viewmode available.
 language:  To specify language if not it will take default site language.

Examples 

  • {{ drupal_field('field_image', 'node', 1, 'teaser') }} to display the field_image value of node 1 with teaser view mode.
  • {{ drupal_field('field_image', 'node', 1, {type: 'image_url', settings: {image_style: 'large'}}) }} to display the image field value with more detailed settings in a template.

Menu

To print the menu items in a template, we use the twig tweak as below.

Syntax {{ drupal_menu(menu_name, level , depth, expand) }} 
Arguments

 menu_name : Machine name of the menu
 level:  Menu level to display default value is 1.
 depth: Maximum number of menu levels to display   default is 0.
 expand: To allow the user to select whether it is expanded or not. Default is false.

Example
{{ drupal_menu('main_navigation') }} to render the menu with its default values.

Form

To render the Drupal form in a template we can implement the twig tweak as below.

 Syntax {{ drupal_form(form_id. args ….) }}
Arguments

 form_id: Form id of the form that you want to display in template.
 args:  Optional arguments that can be passed to the constructor.

Example
{{ drupal_form('Drupal\\system\\Form\\CronForm') }} to display the form in a twig template by providing the path to its class.

Image

There are several ways of rendering images in twig. Some easy ways with using twig tweaks are as follows.

Syntax {{ drupal_image(property_id, style, attribute, responsive, access_chek) }}
Arguments

 property_id: It is the unique id of the image i.e fid, uuid or file_uri.
 style : Image style of the image.
 attribute : For providing the attributes to the image such as alt, title etc.
 responsive : To indicate the image style is responsive image style.
 access_chek : To specify the access check is required.

Examples 

  • {{ drupal_image(123) }} this will render the original image whose fid is 123.
  • {{ drupal_image('9bb27144-e6b2-4847-bd24-adcc59613ec0') }} this will render the image using the unique uuid of the image.

  • {{ drupal_image('public://2020/05/ocean.jpg') }} to render the image using the file uri of the image.

  • {{ drupal_image('public://2020/05/ocean.jpg', 'thumbnail', {alt: 'The alternative text'|t, title: 'The title text'|t}) }} here is an example of displaying an image thumbnail by adding the alt and title for the image. Note : uri path will be based on the default files location since it is set to sites/default/files/2020/05/ocean.jpg.

Token

Drupal 8 introduced tokens which are very useful and huge time savers for Drupal developers. From twig tweak we can render the tokens as below. 

 Syntax {{ drupal_token(token, data, options) }}
 Arguments

 token : Name of the token to be printed.
 data: Array of values used for replacement of tokens.
 options: This also used as a flag when replacing tokens.

Examples
{{ drupal_token('site:name') }} to display the site name using the tokens in twig

Configurations

Printing the configuration values in twig will be very useful in a site where you need dynamic data to be printed according to the configurations.

Syntax  {{ drupal_config(config_name, key) }}
Arguments

 config_name: Name of the configuration yml file.
 key:  Specific value to be printed from the configuration

Example
{{ drupal_config('system.site', 'name') }} to print the name of the site from system.site.yml configuration into a template.

Dump

Debugging is the most important part of the development process. Here are some quick and cool methods to debug in twig. It needs Symfony var dumper component. It can be installed from composer by $ composer require --dev symfony/var-dumper 

Syntax {{ drupal_dump(var) }} 
Arguments var : to print the specific arguments in a template. If a variable is not provided, then all the variables inside the template will be printed. dd() is the shorthand for the method.

Example
{{ dd(var) }} this will  dump the var data from a template.

Drupal Title

To get the title of the current route we can use the twig as below.

Example
{{ drupal_title() }} this will print the title of the current route.

Drupal URL

To generate a URL from an internal path inside the twig we can use the twig tweak snippet as below.

Syntax {{ drupal_url(input, options, access_check) }}
Arguments

 Input : use input link path.
 options : array of options including query params.
 access_check: to check the access default is false.

 

Example
{{ drupal_url('node/1', {query: {foo: 'bar'}, fragment: 'example', absolute: true}) }} this will return the https://site_name/node/1?foo=bar#example as output.

Drupal Link

It generates the link path if the URL is not accessible to the user. It works the same as Drupal URL but with extra attributes.

 Syntax {{ drupal_link(text, input, options, access_check) }}
Arguments

 text : Text to be displayed.
 Input : use input link path.
 options : array of options including query params
 access_check : to check the access default is false.

Example
{{ drupal_link('View'|t, 'node/1', {attributes: {target: '_blank'}}) }} this will create a link with name View and also has an option to open the link in the new tab.

Drupal Messages

To display the Drupal status messages in template, find the example below.

Example
{{ drupal_messages() }} will display status based on user actions in the site.

Drupal Breadcrumbs

To display the breadcrumbs of the site in template as below, find the example below.

Example
{{ drupal_breadcrumb() }} This will display the breadcrumbs block in template.

Drupal Breakpoints

To add a debug point to a twig template is as below.

Example
{{ drupal_breakpoint() }} This will add a breakpoint in the template where you have added it.

Token Replace Filter

To replace all the tokens in a given string with appropriate values.

Example
{{ 'h1>[site:name]h1>div>[site:slogan]div>'|token_replace }} this will replace the tokens available in a string with its appropriate values.

Preg replace filter

It will perform a regular expression search on the text and replaces it with the options.

Syntax {{ text | preg_replace('(pattern)',replacement) }}
Arguments text : Text where the searching and replacing should   happen.
 pattern:  Text that should replace in an input.
 replacement: Replacement text to replace.

Example
{{ 'foo' | preg_replace('(foo)', 'bar') }} in this example “foo” is getting replaced with bar

Image style filters

It will return the image URL with the downloaded image style.

Syntax {{ image_uri|image_style(style) }}
Arguments image_uri : File uri of the image field.
 style : the style which you want to apply for the image.

Example
{{ 'public://images/ocean.jpg'|image_style('thumbnail') }} this will apply the thumbnail image style to the given image.

Transliterate filter

It will Transliterate text from Unicode to US-ASCII and replace unknown characters with “?” by default.

Syntax{{ text|transliterate(language,unknown_chars,maxlength) }} 
 Arguments 

 text : The text which needs to be translated.
 language: language code for which it should translate default is en(English).
 unknown_chars: The character which needs to be replaced with unknown character   default is “?”. 
 maxlength: Max length of word that should check for the translation.

Example
{{ 'Привет!'|transliterate }} this will return the output in english that is “Private!”.

Check markup filter

Apply the enabled filters for the text provided.
 

Syntax {{ text | check_markup(format_id, language,filters_to_skip) }}
 Arguments

 text : the text for which the filters should get applied.
 format_id : id of the text format should be used.
 language:  language to which the formatter should apply.
 filters_to_skip: array of filters to skip defaults to [].

Example
{{ 'b>boldb> strong>strongstrong>' | check_markup('restricted_html') }} This will apply the 'restricted_html' filter for the text given.

Truncate filter

This will be used to truncate the strings to a specified number of characters.

Syntax {{ text | truncate(max_length,word_safe,add_ellipsis,word_safe_len) }}
Arguments

 text : text to be truncated.
 max_length : max length of text to be truncated.
 word_safe : boolean value to truncate at the end defaults to False;
 add_ellipsis: add … to the end of the text default is False. 

 Word_safe_len : if word_safe is true this option will specify the min length.

Example
{{ 'Some long text' | truncate(10, true) }} This will truncate the text to 10 characters and also truncate on boundary.

With Filter

This will add new elements to the array. It also returns an array with modified value.

Example
{{ content.field_image | with('#title', 'Photo' | t) }} This will add a title to the field image and returns.

Children Filter

To filter out the child elements of the render array in a twig template. Also, this will have an option to sort the elements by its weight. This will be useful when processing individual fields.

Example
{{ node.field_example|children }} this will render all the child elements of field_example in template.

File Uri and Url filter

These both filters will be used when dealing with images in twig. You can get the image Uri and URL using these methods in twig tweak.

Example

  • {{ node.field_image | file_url }} returns the absolute url of the image file.
  • {{ node.field_image | file_uri }} returns the uri of the image file relative to its sites/default/files directory.
Shefali ShettyApr 05, 2017