On this page
- Drupal View
- Drupal View Result
- Drupal Block
- Drupal Region
- Drupal Entity
- Drupal Entity Form
- Drupal Field
- Drupal Menu
- Drupal Form
- Drupal Image
- Drupal Token
- Drupal Config
- Drupal Dump
- Drupal Title
- Drupal URL
- Drupal Link
- Drupal Messages
- Drupal Breadcrumb
- Drupal Breakpoint
- Contextual Links
- Token Replace Filter
- Preg Replace Filter
- Image Style Filter
- Transliterate Filter
- Check Markup Filter
- Truncate Filter
- View Filter
- With Filter
- Children Filter
- File URL Filter
- File URI Filter
- PHP Filter
Cheat sheet
This cheat sheet lists all the filters and functions provided by the 8.x-2.x branch of the Twig Tweak contrib module.
For the 3.x branch, use the cheat sheet in the project repo.
Drupal View
Render a view. See Twig Tweak and Views page for more information.
Accepted parameters:
$name
- String - Required - The name of the view to embed.
$display_id
- String - Optional - The display id to embed. Default is
default
. $...
- Mixed - Optional - Any additional parameters will be passed as arguments.
{{ drupal_view('who_s_new', 'block_1') }}
Drupal View Result
Get the result of a view.
Accepted parameters:
$name
- String - Required - The name of the view to embed.
$display_id
- String - Optional - The display id to embed. Default is
default
. $...
- Mixed - Optional - Any additional parameters will be passed as arguments.
{{ drupal_view_result('who_s_new', 'block_1') }}
Drupal Block
Used to render a block. See Rendering blocks with Twig Tweak page for more information and examples:
Drupal Region
Used to render contents of a region from the default or any other specified theme.
Accepted parameters:
$region
- String - Required - The Region to build.
$theme
- String - Optional - The name of the theme to load the region. If it is not provided then default theme will be used.
Example usage
{# Print 'Sidebar First' region of the default site theme. #}
{{ drupal_region('sidebar_first') }}
{# Print 'Sidebar First' region of Bartik theme. #}
{{ drupal_region('sidebar_first', 'bartik') }}
Drupal Entity
Used to render an entity. Returns NULL
if the entity doesn't exist.
Accepted parameters:
$entity_type
- String - Required - The entity type (
node
,block
,webform
etc). $id
- Mixed - Optional - The ID of the entity to build.
$view_mode
- String | Array - Optional - Can be either the name of a view mode, or an array of display settings. Defaults to
default
. $langcode
- String - Optional - For which language the entity should be rendered, defaults to the current content language.
$check_access
- Bool - Optional - Indicates that access check is required, defaults to
TRUE
.
Example usage
{# Print a content block which ID is 1. #}
{{ drupal_entity('block_content', 1) }}
{# Print a node's teaser. #}
{{ drupal_entity('node', 123, 'teaser') }}
{# Print Branding block which was previously disabled on #}
{# admin/structure/block page. #}
{{ drupal_entity('block', 'bartik_branding', check_access=false) }}
Drupal Entity Form
Gets the built and processed entity form for the given entity type.
Accepted parameters:
$entity_type
- String - Required - The entity type (
node
,block
,webform
etc). $id
- Mixed - Optional - The ID of the entity to build. If empty then new entity will be created.
$form_mode
- String - Optional - The mode identifying the form variation to be returned. Defaults to
default
. $values
- Array - Optional - An array of values to set, keyed by property name. Defaults to
[]
$check_access
- Bool - Optional - Indicates that access check is required, defaults to
TRUE
.
Example usage
{# Print edit form for node 1. #}
{{ drupal_entity_form('node', 1) }}
{# Print add form for Article content type. #}
{{ drupal_entity_form('node', values={type: 'article'}) }}
{# Print user register form. #}
{{ drupal_entity_form('user', NULL, 'register', check_access=false) }}
{# Print `feedback` contact form. #}
{{ drupal_entity_form('contact_message', values={contact_form: 'feedback'}) }}
Drupal Field
Returns the render array for a single entity field, or NULL
if the field value doesn't exist.
Accepted parameters:
$field_name
- String - Required - The field name.
$entity_type
- String - Required - The entity type.
$id
- Mixed - Required - The ID of the entity to render. If using in a template for multiple nodes, use
node.id
. $view_mode
- String | Array - Optional - Can be either the name of a view mode, or an array of display settings. Defaults to
default
. $langcode
- Array - Optional - Language code to load the translation.
$check_access
- Bool - Optional - Indicates that access check is required, defaults to
TRUE
.
Example usage
{# Contents of field_image from node with the ID of 1. #}
{{ drupal_field('field_image', 'node', 1) }}
{# Contents of field_image from node with the ID of 1. Render using 'teaser' view-mode (as configured for node 1's content type) #}
{{ drupal_field('field_image', 'node', 1, 'teaser') }}
{# Contents of field_image from node with the ID of 1. With more detailed configuration. Configuration options vary depending on the type of field and widgets available. #}
{{ drupal_field('field_image', 'node', 1, {type: 'image_url', settings: {image_style: 'large'}}) }}
Drupal Menu
Returns a render array for the specified menu.
Accepted parameters:
$menu_name
- String - Required - The menu name.
$level
- Int - Optional - Initial menu level. Defaults to
1
. $depth
- int - Optional - Maximum number of menu levels to display. Defaults to
0
$expand
- Bool - Optional - Whether to expand all menu links. Defaults to
FALSE
.
Example usage
{# Render the menu with the defaults. #}
{{ drupal_menu('main') }}
Drupal Form
Returns a render array to represent the form.
Accepted parameters:
$form_id
- String - Required - The fully qualified form class.
$...
- Additional arguments are passed to form constructor.
Example usage
{{ drupal_form('Drupal\\search\\Form\\SearchBlockForm') }}
Drupal Image
Used to build the image.
Accepted parameters:
$property
- Mixed - Required - A property to identify the image. Could be
fid
,uuid
or auri
. If a URI is provided, it should be relative to your public files directory (which is usuallysites/default/files
). If your file has a path likesites/default/files/2020/05/ocean.jpg
, you should providepublic://2020/05/ocean.jpg
$style
- String - Optional - Image style to use
$attributes
- Array - Optional - Image attributes. Defaults to
[]
$responsive
- Bool - Optional - Indicates that the provided image style is responsive.
- Hint: Due to a Drupal Core limitation, the responsive option will just print out the fallback image style as simple img.
$check_access
- Bool - Optional - Indicates that access check is required.
Example usage
{# Render image specified by file ID. #}
{{ drupal_image(123) }}
{# Render image specified by file UUID. #}
{{ drupal_image('9bb27144-e6b2-4847-bd24-adcc59613ec0') }}
{# Render image specified by file URI. This is relative to default sites directory. If your file has the path `sites/default/files/2020/05/ocean.jpg`, drop the default sites directory bit. #}
{{ drupal_image('public://2020/05/ocean.jpg') }}
{# Render image using 'thumbnail' image style and custom attributes. #}
{{ drupal_image('public://2020/05/ocean.jpg', 'thumbnail', {alt: 'The alternative text'|t, title: 'The title text'|t}) }}
{# Render responsive image. #}
{{ drupal_image('public://2020/05/ocean.jpg', 'wide', responsive=true) }}
Drupal Token
Replaces a given token with appropriate value.
Accepted parameters:
$token
- String - Required - A replaceable token.
$data
- Array - Optional - An array of keyed objects. For simple replacement scenarios
node
,user
, and others are common keys, with an accompanying node or user object being the value. Some token types, likesite
, do not require any explicit information from $data and can be replaced even if it is empty. $options
- Array - Optional - A keyed array of settings and flags to control the token replacement process.
Example usage
{{ drupal_token('site:name') }}
Drupal Config
Retrieves data from a given configuration object.
Accepted parameters:
$name
- String - Required - The name of the configuration object to construct.
$key
- String - Required - A string that maps to a key within the configuration data.
Example usage
{{ drupal_config('system.site', 'name') }}
Drupal Dump
Dumps information about variables. Alias dd()
could be used instead of drupal_dump()
. You need to install Symfony VarDumper component.
Accepted parameters:
$context
- Array - Required - Variables from the Twig template.
$variable
- Mixed - Optional - The variable to dump.
Example usage
{# Basic usage. #}
{{ drupal_dump(var) }}
{# Same as above but shorter. #}
{{ dd(var) }}
{# Dump all available variables for the current template. #}
{{ dd() }}
Drupal Title
Returns a title for the current route.
Example usage
{# Usage. #}
{{ drupal_title() }}
Drupal URL
Generates and returns a URL object from an internal path or NULL
if URL is not accessible to the user.
Accepted parameters:
$user_input
- String - Required - User input for a link or path.
$option
- Array - Optional - An array of options. Defaults to
[]
. $check_access
- Bool - Optional - Indicates that access check is required. Defaults to
FALSE
Example usage
{# Basic usage. #}
{{ drupal_url('node/1') }}
{# Complex URL. #}
{# Returns https://example.com/node/1?foo=bar#example #}
{{ drupal_url('node/1', {query: {foo: 'bar'}, fragment: 'example', absolute: true}) }}
Drupal Link
Generates and returns a link object from an internal path or NULL
if URL is not accessible to the user.
Accepted parameters:
$text
- String - Required - The text to be used for the link.
$user_input
- String - Required - User input for a link or path.
$option
- Array - Optional - An array of options. Defaults to
[]
. $check_access
- Bool - Optional - Indicates that access check is required. Defaults to
FALSE
Example usage
{# It supports the same options as drupal_url(), plus attributes. #}
{{ drupal_link('View'|t, 'node/1', {attributes: {target: '_blank'}}) }}
{# This link will only be shown for privileged users. #}
{{ drupal_link('Example'|t, '/admin', check_access=true) }}
Drupal Messages
Displays status messages.
Example usage
{{ drupal_messages() }}
Drupal Breadcrumb
Builds the breadcrumb.
Example usage
{{ drupal_breadcrumb() }}
Drupal Breakpoint
Emits a breakpoint to the debug client.
Accepted parameters:
$environment
- \Twig_Environment - Required - The Twig environment instance.
$context
- Array - Required - Variables from the Twig template.
Example usage
{{ drupal_breakpoint() }}
Contextual Links
Returns a renderable array representing contextual links.
Accepted parameters:
$id
- String - Required - A serialized representation of a #contextual_links property value array.
Example usage
{# Basic usage. #}
{{ drupal_contextual_links('entity.view.edit_form:view=frontpage&display_id=feed_1:') }}
{# Multiple links. #}
{{ drupal_contextual_links('node:node=123|block_content:block_content=123:') }}
Token Replace Filter
Replaces all tokens in a given string with appropriate values and returns the HTML.
Accepted parameters:
$text
- String - Required - An HTML string containing replaceable tokens.
Example usage
{# Basic usage. #}
{{ '<h1>[site:name]</h1><div>[site:slogan]</div>'|token_replace }}
{# This is more suited to large markup (requires Twig >= 1.41). #}
{% apply token_replace %}
<h1>[site:name]</h1>
<div>[site:slogan]</div>
{% endapply %}
Preg Replace Filter
Performs a regular expression search and replace. For simple string interpolation consider using built-in replace
or format
Twig filters.
Accepted parameters:
$text
- String - Required - The text to search and replace.
$pattern
- String - Required - The pattern to search for.
$replacement
- String - Required - The string to replace.
Example usage
{{ 'Drupal - community plumbing!' | preg_replace('/(Drupal)/', '<b>$1</b>') }}
Image Style Filter
Returns the URL of this image derivative for an original image path or URI. The returned value is the absolute URL where a style image can be downloaded, so it's suitable for use in an <img>
tag. Requesting the URL will cause the image to be created.
Accepted parameters:
$path
- String - Required - The path or URI to the original image. The path should be relative to your public files directory (which is usually
sites/default/files
). If your file has a path likesites/default/files/2020/05/ocean.jpg
, you should providepublic://2020/05/ocean.jpg
$style
- String - Required - The image style.
Example usage
{{ 'public://images/ocean.jpg'|image_style('thumbnail') }}
Transliterate Filter
Transliterates text from Unicode to US-ASCII. Returns a string with non-US-ASCII characters transliterated to US-ASCII characters, and unknown characters replaced with $unknown_character
.
Accepted parameters:
$string
- String - Required - The string to transliterate
$langcode
- String - Optional - The language code of the language the string is in. Defaults to
en
if not provided. Warning: this can be unfiltered user input. $unknown_character
- String - Optional - The character to substitute for characters in
$string
without transliterated equivalents. Defaults to?
. $max_length
- Int - Optional - If provided, return at most this many characters, ensuring that the transliteration does not split in the middle of an input character's transliteration.
Example usage
{# Will return "Privet!" #}
{{ 'Привет!'|transliterate }}
Check Markup Filter
Runs all the enabled filters on a piece of text.
Accepted parameters:
$text
- String - Required - The text to be filtered.
$format_id
- Mixed - Optional - The machine name of the filter format to be used to filter the text. Defaults to the fallback format. See
filter_fallback_format()
(api.drupal.org page). $langcode
- String - Optional - The language code of the text to be filtered.
$filter_types_to_skip
- Array - Optional - An array of filter types to skip, or an empty array (default) to skip no filter types.
Example usage
{{ '<b>bold</b> <strong>strong</strong>' | check_markup('restricted_html') }}
Truncate Filter
Truncates a UTF-8-encoded string safely to a number of characters.
Accepted parameters:
$string
- String - Required - The string to truncate.
$max_length
- Int - Optional - An upper limit on the returned string length, including trailing ellipsis if
$add_ellipsis
is TRUE. $wordsafe
- Bool - Optional - If TRUE, attempt to truncate on a word boundary. Defaults to
FALSE
. $add_ellipsis
- Bool - Optional - If TRUE, add
...
to the end of the truncated string. $min_wordsafe_length
- Int - Optional - If $wordsafe is
TRUE
, this indicates minimum acceptable length for truncation.
Example usage
{{ 'Some long text' | truncate(10, true) }}
View Filter
Returns a render array for entity, field list or field item.
Accepted parameters:
$object
- Mixed - Required - The object to build a render array from.
$display_options
- String | Array - Optional - Can be either the name of a view mode, or an array of display settings. Defaults to
default
. $langcode
- String - Optional - For which language the entity should be rendered, defaults to the current content language.
$check_access
- Bool - Optional - Indicates that access check is required. Defaults to
FALSE
Example usage
{# Do not put this into node.html.twig template to avoid recursion. #}
{{ node | view }}
{{ node | view('teaser') }}
{{ node.field_image | view }}
{{ node.field_image[0] | view }}
{{ node.field_image | view('teaser') }}
{{ node.field_image | view({settings: {image_style: 'thumbnail'}}) }}
With Filter
Adds new element to the array and returns the modified array.
Accepted parameters:
$build
- Array - Required - The renderable array to add the child item.
$key
- Mixed - Optional - The key of the new element.
$element
- Mixed - Optional - The element to add.
Example usage
{# Set top level value. #}
{{ content.field_image | with('#title', 'Photo' | t) }}
{# Set nested value. #}
{{ content | with(['field_image', '#title'], 'Photo' | t) }}
Children Filter
Filters out the children of a render array, optionally sorted by weight.
Accepted parameters:
$build
- Array - Required - The render array whose children are to be filtered.
$sort
- Bool - Optional - Boolean to indicate whether the children should be sorted by weight. Defaults to
FALSE
Example usage
<ul>
{% for tag in content.field_tags|children %}
<li>{{ tag }}</li>
{% endfor %}
</ul>
File URL Filter
For string arguments it works similar to core file_url() Twig function. When field item list passed the URL will be extracted from the first item. In order to get URL of specific item specify its delta explicitly using array notation.
Accepted parameters:
$input
- String | Object - Required - Can be either file URI or an object that contains the URI. If a URI is passed, it should be relative to your public files directory (which is usually
sites/default/files
). If your file has a path likesites/default/files/2020/05/ocean.jpg
, you should providepublic://2020/05/ocean.jpg
Example usage
{{ 'public://2020/05/ocean.jpg' | file_url }}
{{ node.field_image | file_url }}
{{ node.field_image[0] | file_url }}
{{ node.field_media | file_url }}
File URI Filter
Returns a file URI string. When a field item list is passed, the URI will be extracted from the first item. In order to get URL of specific item, specify its delta using array notation.
Media fields are fully supported including OEmbed resources, in which case it will return the URL to the resource, similar to the file_url
filter.
Accepted parameters:
$input
- Object - Required - A field or field item that references a file or media entity.
Example usage
{{ node.field_image|file_uri }}
{{ node.field_image[0]|file_uri }}
{{ node.field_media|file_uri }}
Useful to apply the image_style
filter to Media fields. (Remember to check whether a URI is actually returned.)
{% set media_uri = node.field_media|file_uri %}
{% if media_uri is not null %}
{{ media_uri|image_style('thumbnail') }}
{% endif %}
PHP Filter
Evaluates a string of PHP code and returns the result. PHP filter is disabled by default. To enable, you should add the following line to your settings.php
.
$settings['twig_tweak_enable_php_filter'] = TRUE;
Accepted parameters:
$code
- String - Required - Valid PHP code to be evaluated.
Example usage
{{ 'return date('Y');' | php }}
{# Using PHP filter is discouraged as it may cause security implications. In fact it is very rarely needed. #}
{# The above code could be replaced with the following #}
{{ 'now' | date('Y') }}
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion