Drupal 8 Tutorial #43 : Twig Tweak Module (Article + Video)

Submitted by TheMain on Wed, 08/24/2016 - 13:00

Twig Tweak module adds some useful functions and filters to use in templates.

How to install it?

drush -y en twig_tweak

Print views in templates

{{ drupal_view('latest_posts', 'default') }}

You can use arguments:

{{ drupal_view('latest_posts', 'default', '81,60') }}


View machine name.


Display ID (default, block_1 etc).


(optional) Arguments. Example: add an ID contextual filter to the view and you can limit the view results for only selected nodes (81 and 60 in this case).

Note: this function uses Views Embed View function that doesn't display the title of the view. You can print it manually above the view or use the drupal_block function below (if you don't use arguments).

Print blocks in templates

{{ drupal_block('mytheme_search') }}


The machine name of the block.

Print tokens in templates

{{ drupal_token('site:name') }}

Example tokens:


Site name.


Site slogan.


Current date in long format

Note: you can install Token module to see all available tokens in here: admin/help/token.

Token module

Use token_replace filter to print out multiple tokens at once:

{{ '[site:name] [current-date:long]' | token_replace | raw }}

[site:name] [current-date:long]

The tokens.


The filter.


I had to use this filter for the HTML tags to show up right.

You can also access configuration data with drupal_config:

{{ drupal_config('system.site', 'name') }

PHP filter

{{ 'return date("Y d m");' | php }}

Note: allowing PHP like this in templates can create security holes and perfomance issues. Read more about the PHP Filter module:

Search and replace with regular expressions

{{ 'some text' | preg_replace('some', 'other') | raw }}

This replaces the word some with other.

some text

The text to apply search and replace.


The text to look for.


The replacement.


I had to use raw filter to make it work.

Render entities

Note: at this moment (2016.08.24) with the stable version: 8.x-1.2 this function seemed to get stuck in a loading screen.

This will render the whole node:

{{ drupal_entity('node', 1) }}

This will render the teaser:

{{ drupal_entity('node', 1, 'teaser') }}

This will render the current node:

{{ drupal_entity('node', NULL, 'teaser') }}


The entity type.


Entity ID.


The view mode.

Check the video to see it in action

In the video I also use Bootstrap to divide node content into two columns and show Recent Posts view next to the body field.

Sources & links:
Module page: https://www.drupal.org/project/twig_tweak
Issue queue: https://www.drupal.org/project/issues/twig_tweak?status=All&categories=All
Documentation: http://cgit.drupalcode.org/twig_tweak/tree/src/TwigExtension.php

Posted by Samuli Natri on 24 August 2016