Twig Tweak module provides a Twig extension with some useful functions and filters that can improve development experience.

<dl class="examples">

  {# This accepts views arguments as well. #}
  <dt>View:</dt>
  <dd>{{ drupal_view('who_s_new', 'block_1') }}</dd>

  {# The block should be configured on "admin/structure/block" page. #}
  <dt>Block:</dt>
  <dd>{{ drupal_block('bartik_powered') }}</dd>

  {# Pass theme name as a second argument if needed. #}
  <dt>Region:</dt>
  <dd>{{ drupal_region('sidebar_first') }}</dd>

  {# It can be any content entity. #}
  <dt>Entity:</dt>
  <dd>{{ drupal_entity('block_content', 1) }}</dd>

  {# Load an entity from the current route. #}
  <dt>Entity from route:</dt>
  <dd>{{ drupal_entity('node', null, 'teaser') }}</dd>

  {# Render a single entity field. #}
  <dt>Field:</dt>
  <dd>{{ drupal_field('field_image', 'node', 1) }}</dd>

  {# Expand menu items to display the entire menu tree. #}
  <dt>Menu:</dt>
  <dd>{{ drupal_menu('main') }}</dd>

  {# Specify menu level and depth. #}
  <dt>Part of menu:</dt>
  <dd>{{ drupal_menu('admin', 2, 3) }}</dd>

  {# Slashes should be escaped. #}
  <dt>Form:</dt>
  <dd>{{ drupal_form('Drupal\\search\\Form\\SearchBlockForm') }}</dd>

  {# Use token API to deliver data to your templates. #}
  <dt>Token:</dt>
  <dd>{{ drupal_token('site:name') }}</dd>}

  {# Tokens can be extracted from the context. #}
  <dt>Token with context:</dt>
  <dd>{{ drupal_token('node:title', {node: node}) }}</dd>

  {# Another way to get site name. #}
  <dt>Config:</dt>
  <dd>{{ drupal_config('system.site', 'name') }}</dd>

  {# This works even if Twig debug mode is disabled. #}
  <dt>Dump variable:</dt>
  <dd>{{ drupal_dump(var) }}</dd>

  {# Same as previous but shorter. #}
  <dt>Dump variable (alias):</dt>
  <dd>{{ dd(var) }}</dd>

  {# This may break cacheability. #}
  <dt>Set status message:</dt>
  <dd>{{ drupal_set_message('Hello world!') }}</dd>

  {# The title is cached per URL. #}
  <dt>Page title:</dt>
  <dd>{{ drupal_title() }}</dd>

  {# Welcome back old friend! #}
  <dt>PHP filter:</dt>
  <dd class="bad-practice">© {{ 'return date("Y");' | php }}</dd>

  {# Replace multiple tokens at once. #}
  <dt>Token replace:</dt>
  <dd>{{ '<h1>[site:name]</h1><div>[site:slogan]</div>' | token_replace }}</dd>

  {# The easiest way to alter their output. #}
  <dt>Preg replace:</dt>
  <dd>{{ 'Drupal - community plumbing!' | preg_replace('(Drupal)', '<b>$1</b>') }}</dd>

  {# The filter processes either path or URI to original image. #}
  <dt>Image style:</dt>
  <dd>{{ 'public://images/ocean.jpg' | image_style('thumbnail') }}</dd>

</dl>

Notes

To make use of drupal_dump() install Symfony VarDumper component.

Since version 1.3 PHP filter is disabled by default. You can enable it in settings.php file as follows: $settings['twig_tweak_enable_php_filter'] = TRUE;.

Recommended modules

Snippet manager module can be used as a sandbox to play with Twig.

Project Information

Downloads