Skip to main content
Appic Softwares Logo - Custom Software and App Development Company
  • AI/ML
  • Services
  • Industries
  • Platform
  • Hire Talent
  • Our Company
  • Blog
Contact Us
HomeBlogDrupal

How To Get Started With Twig With Drupal 9?

Nitesh Jain
Sep 15, 2023
Back to Blog

Table of Contents

  • Implementing the Twig Tweak Module in Drupal 9
  • Leveraging Drupal 9’s Twig Tweak Functions and Filters
  • Conclusion

Share this

How To Get Started With Twig With Drupal 9?

With the advent of Drupal 9 and the evolution of web development practices, tools like the Twig Tweak module have become indispensable for Drupal writers. This module streamlines the handling of advanced Twig templates, offering various features and filters that enhance developer efficiency and code clarity. Whether you’re creating custom themes or modules, Twig Tweak facilitates quick and intuitive Drupal development by ensuring well-structured and readable code.

As Drupal 8 reaches its end of life, transitioning to Drupal 9 has become imperative. However, if you’re still navigating the process of crafting custom modules in Drupal 8, rest assured that familiar methods and techniques remain effective.

Implementing the Twig Tweak Module in Drupal 9

You can download and install the module from here or from the composer. Once you’ve downloaded the file and extracted it, put it in the project location. You can also download using C
omposer with the following code – 

composer require drupal/twig_tweak

Source: Specbee

Go to Extend and turn on the feature from there. Even a brush can be used to turn on the gadget.

Read this:- Step By Step Guide To Create Multi-Site In Drupal With Lando

Leveraging Drupal 9’s Twig Tweak Functions and Filters

Results of views and views

We can use the twig tweak piece shown below to show the views in the twig template.

Sentence structure:

{{ drupal_view(views_name, display_id, args…) }}

{{ drupal_view_result(views_name, display_id) }}

Source: Specbee

The Cases:

views_name: The name of the machine for the views. display_id: The current display’s machine name. args: Filter inputs that are not required.

Some Examples

rupal_view(‘who_s_new’, ‘block_1’): This will put the who’s new views block_1 in a template.

drupal_view(‘who_s_new’, ‘block_1’, ‘arg_1’, ‘arg_2’): If contextual filters are added, extra arguments can be sent along with sending arguments.

{% set view = drupal_view_result(‘related’, ‘block_1’)|length %}

“% if view is greater than 0%”

{{ drupal_view(‘related’, ‘block_1’) }}

% endif%>

Source: Specbee

This code only shows the view if it has results in a template.

Keeps out

We can use the piece of twig tweak code below to put the plugin blocks in the template.

Sentence structure: 

{{ drupal_block(‘plugin_id’, {label: ‘Example’|t, some_setting: ‘example’}) }} 

Source: Specbee

The Cases:                                                                                                                                     

plugin_id: The plugin ID of a block can be found in the block’s class comments.

options: The second input is optional and is used to set up the blocks.

Example

{{ drupal_block(‘system_breadcrumb_block’) }} to place the breadcrumbs block in template.

Source: Specbee

Region

To show the contents of an area based on the default theme or a specific theme.

Sentence structure:                                                                                                                                                       

{{ drupal_region(region_name, theme_name) }}

Source: Specbee

The Cases:                                                                                                                            

The name of the region’s machine can be found in the info.yml file.                       

theme_name: The name of a theme to use if you don’t want the default theme to be used.

Example

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

Source: Specbee

Entity and the form of Entity

Use the code below to show the possible entity and entity form in a Twig template.

Sentence structure:                                                                                                                     

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

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

Source: Specbee

The Cases:                                                                                                                                   

  • entity_type: The type of an entity, such as node, block, block_content, webform, text, etc. Id: The ID of an entity.                                                  view_mode: To look at the object based on its viewmode.                                                     
  • language: If you don’t choose a language, the site will use the default language.                                             
  • access_check: To check if a block can be accessed, the default answer is true.                                                 
  • form_mode: To see the form of an object based on its formmode.                                                             
  • values: The default for an array of property values is [].

Some Examples

In a twig template, you can use drupal_entity(‘block_content’, 1) to show the content block whose id is 1.

drupal_entity(‘node’, 123, ‘teaser’) shows the node teaser info of the entity with id 123.

To show the node edit entity form in a template, use drupal_entity_form(‘node, 1’).

drupal_entity_form(‘node’, values=’type:’article’) shows the node add form for the type article.

The field

Use the following snippet of twig tweak code to show or get the field value of any object in a twig template.

Sentence structure:

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

Source: Specbee

The Cases:                                                                                                                               

field_name: The field’s machine name.

entity_type: The type of an entity, such as a node, block, block_content, webform, text, etc.

Id: The id of a thing.

view_mode: The mode by which the entity can be seen.

language: If you don’t choose a language, the site will use the default language.

Some Examples 

drupal_field(‘field_image’, ‘node’, 1, ‘teaser’) shows the field_image value of node 1 in teaser view mode.

drupal_field(‘field_image’, ‘node’, 1, ‘type: ‘image_url’, settings: ‘image_style: ‘large’) is used in a template to show the image field value with more settings.

Menu

We use the twig tweak below to show the menu items in a template.

Sentence structure:

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

Source: Specbee

The Cases:                                                                                                                                  

menu_name: The name of the menu on the machine

level: The default number for the level menu to show is 1.

depth: 0 is the maximum number of menu options that can be shown by default.

expand: To give the person the choice of whether or not to expand it. False is the default.

Example

{{ drupal_menu(‘main_navigation’) }} to render the menu with its default values.

Form

We can use the twig tweak below to make the Drupal form show up in a design.

Sentence structure:                                                                                                                         

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

Source: Specbee

The Cases:                                                                                                                                       

orm_id: The form’s id that you want to show in the script.

args: Arguments that can be passed to the constructor, but they are not required.

Example

{{ drupal_form(‘Drupal\\system\\Form\\CronForm’) }}

Source: Specbee

to display the form in a twig template by providing the path to its class.

Image

There are different ways to show pictures in twigs. Here are a few simple ways to use twig tweaks.

Sentence structure:

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

Source: Specbee

The Cases:

It is the image’s unique ID, which could be a fid, uuid, or file_uri.

style: The way the picture looks.

attribute: This is used to give the picture its attributes, such as alt, title, etc.

responsive: To show that the style of the picture is responsive.

access_chek: The access check needs to be specified.

Some Examples 

If you type drupal_image(123), the original image with the fid of 123 will be shown.

drupal_image(“9bb27144-e6b2-4847-bd24-adcc59613ec0”) will show the image using the image’s unique uuid.

drupal_image(‘public://2020/05/ocean.jpg’) will use the file URI to show the image.

drupal_image(‘public://2020/05/ocean.jpg’, ‘thumbnail’, ‘alt: ‘The alternative text’, title: ‘The title text’) is an example of how to show an image thumbnail by adding the image’s alt and title. Note: Since the URI path is set to sites/default/files/2020/05/ocean.jpg, it will use the default files folder.

Token

Tokens were added to Drupal 8 and are very useful and save a lot of time for Drupal writers. From the twig tweak, we can get the following numbers. 

Sentence structure:

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

Source: Specbee

The Cases:

token: The name of the token that will be written.

data: An array of values that can be used to change tokens.

This is also used as a flag when coins are being changed.

Some Examples

drupal_token(‘site:name’) is used to show the site name in Twig using tokens.

Configurations

Printing the setup values in Twig will be very helpful on a site where you need to print dynamic data based on the configurations.

Sentence structure:

drupal_config(config_name, key) says:

The Cases:

config_name: The name of the setup yml file.

key: A number from the configuration to be printed.

For instance

drupal_config(‘system.site’, ‘name’) is used to print the name of the site from the system.site.yml setup file into a template.

Dump

The most important part of the development process is fixing bugs. Here are some cool and quick ways to fix bugs in Twig. It needs a component called Symfony var dumper. It can be put in place with $ composer require-dev symfony/var-dumper from the composer. 

Sentence structure:

{{ drupal_dump(var) }} 

Source: Specbee

The Cases:

var: Prints the exact arguments in a template. If a variable is not given, all the variables inside the template will be written. The short name for the method is dd().

For instance

This will dump the info from a template’s var variable.

Title of Drupal

We can use the twig as shown below to get the name of the current route.

For instance

With drupal_title(), the title of the current route will be shown.

Drupal URL

We can use the twig tweak piece below to make a URL from an internal path inside the twig.

Sentence structure:

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

Source: Specbee

The Cases:

entry: Use the link path for entry.

options: An array of choices, which may include query parameters.

access_check: to make sure that access is set to false by default.

For instance

drupal_url(‘node/1’, ‘query: ‘foo: ‘bar’, ‘fragment: ‘example’, ‘absolute: true’) will return https://site_name/node/1?foo=bar#example is what comes out.

Link to Drupal

If the person can’t get to the URL, it creates the link path. It works just like a Drupal URL, but it has more information.

Sentence structure:

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

The Cases:

text: The text to be shown.

entry: Use the link path for entry.

options: An array of choices, which may include query parameters.

access_check: to make sure that access is set to false by default.

For instance

drupal_link(‘View’|t, ‘node/1’, ‘attributes: ‘target: ‘_blank’), ‘node/1’); This will make a link called View and give you the option to open it in a new tab.

Messages in Drupal

Find an example of how to show the Drupal progress messages in a template below.

For instance

drupal_messages() will show the state of the site based on what users do on the site.

Breadcrumbs in Drupal

Find the example below if you want your site’s clues to look like the one below.

For instance

drupal_breadcrumb(): This will show the block of breadcrumbs in the template.

Drupal Breakpoints

Here’s how to add a debug point to a twig file.

For instance

drupal_breakpoint(): This will put a stop where you put it in the template.

Change Token Filter

To change the numbers of all the tokens in a given string.

For instance

This will change the tokens in a string with their correct values.

Preg replace filter

It will look for the text using a regular expression and replace it with the options.

Sentence structure:

{{ text | preg_replace(‘(pattern)’,replacement) }}

Source: Specbee

The Cases:

text where the search and replace should be done.

pattern: The text to change in an input field.

replacement: Text to be used instead.

For instance

‘foo’ | preg_replace(‘(foo)’, ‘bar’): “foo” is replaced with “bar” in this case.

Style filters for images

It will send back the image’s URL along with the style that was saved.

Sentence structure:

{{ image_uri|image_style(style) }}

Source: Specbee

The Cases:

image_uri: The image field’s file URI.

style: The style you want the picture to have.

For instance

If you type ‘public://images/ocean.jpg’|image_style(‘thumbnail’), the given image will be given the thumbnail style.

Change the filter

It will change text from Unicode to US-ASCII and swap unknown characters with “?” as a rule.

Sentence structure:

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

Source: Specbee

The Cases:

text: The text that needs to be translated.

language: The code for the language it should be translated into. The default is en (English).

unknown_chars: The character that needs to be changed is “?,” which is the norm for “unknown character.””.

maxlength: The longest word for which the translation should be checked.

For instance

{{ ‘Привeт!’|transliterate’: This will give you the English version of “Private!”.

Source: Specbee

Check markup filter

Apply the filters that are turned on to the text that is given.

Sentence structure:

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

Source: Specbee

The Cases:

text: The text that should have the filters added to it.

format_id: This is the ID of the text format.

language: The language that should be used by the formatter.

filters_to_skip: A list of filters to skip, which is set to [] by default.

For instance

This will apply the’restricted_html’ filter to the given text.

Truncate filter

This is how the strings will be cut off at a certain number of characters.

Sentence structure:

text | truncate(max_length,word_safe,add_ellipses,word_safe_len) 

The Cases:

text: the end of the text.

max_length: The maximum length of text that will be cut off.

word_safe: By default, the boolean value to cut off at the end is False;

For instance

“Some long text” | truncate(10, true) | This will cut the text to 10 characters and also cut on border.

Also read this blog:- The Hourly Rate Of Hiring Drupal Developers From India

Through Filter

This adds more items to the list. It also gives back an array of changes.

For instance

This adds a title to the field image and returns: content.field_image | with(‘#title’, ‘Photo’ | t).

The kids filter

In a twig template, filter out the child parts of the render array. Also, you will be able to sort the parts by how much they weigh. This will help when handling each field on its own.

For instance

node.field_example|children will show all of field_example’s children in the template.

Uri and Url file filter

When pictures are used in twig, both of these filters will be used. With these ways in twig tweak, you can get the image Uri and URL.

For instance

When you call node.field_image | file_url, you get the image file’s absolute URL.

When you call node.field_image | file_uri, you get the URI of the image file related to its sites/default/files directory.

@media (max-width: 1024px) { table { width: 330px !is important;

Conclusion

Twig tweak is a donated Drupal 9 module that makes development easier by giving developers quick and easy functions and filters while keeping the code easy to read. In this piece, I list some of the functions and filters that the Twig tweak module has to offer, as well as some easy tips that will help you use them faster. At Appic Softwares, we offer specialized Drupal services that take advantage of some of Drupal’s best features. Contact us right away to learn how we can help you.

This blog is inspired by <https://www.specbee.com/blogs/twig-tweak-in-drupal-9-functions-and-fil
ters
>

Get Free Consultation Now!

Fill out the form below to get started.

Phone

Related Articles

How AI Agents Are Transforming Financial Markets
2/18/2026

How AI Agents Are Transforming Financial Markets

Financial markets have constantly changed in response to advancements. Electronic trading systems, mobile banking, and other technologies continue to revolutionize how money changes hands. The biggest driver of this change is AI agents in finance. These intelligent systems are no longer just experimental tools being tested by tech companies. They are now the backbone of […]

Read More
7 Use Cases of Predictive Analytics In Finance
2/17/2026

7 Use Cases of Predictive Analytics In Finance

Today, the financial service industry is no longer reliant on simply looking back at previous years of data. Institutions expect that they will be able to not only predict and mitigate risks, but also forecast potential market fluctuations, and provide personalized customer experiences in real time through predictive analytics. Predictive analytics is an important area […]

Read More
OpenAI vs Claude for Enterprise AI Applications
2/16/2026

OpenAI vs Claude for Enterprise AI Applications

The use of Enterprise AI Applications is no longer considered just an experiment or “proof of concept”, but instead they are now vital components of a business as it relates to top line revenue generation and the customer experience, as well as the overall operational effectiveness and the long-term strategy of the company. Companies across […]

Read More

Our Drupal Services

Mobile App Development →AI Development Services →Web Development →E-Commerce Development →

Share Your Ideas Here!

We are all ears!

Get in touch with us

  • Contact info type iconsales@appicsoftwares.com
  • Contact info type icon
    +91 - 8233801424,+91 - 9887354080
  • Contact info type iconlive:appicsoftwares
  • Contact info type icon41/11 Varun Path, New Sanganer Road, Jaipur, Rajasthan
  • Follow Us

Your Partner Everywhere!

Appic Softwares Jaipur office illustration

India

41/11 Varun Path, New Sanganer Road, Jaipur, Rajasthan

Appic Softwares USA office illustration

USA

5 Cowboys Way, Suite 300, Frisco, TX 75034, USA

Appic Softwares Germany office illustration

Germany

Magdalenenstraße 34, 80638 München, Germany

About

  • Our company
  • Blog
  • Portfolio
  • Case Studies
  • Let's connect
  • Career

Services

  • iOS App Development
  • Android App Development
  • Software Development
  • Flutter App Development
  • Mobile App Development
  • Ionic development
  • Maintenance & Support

Portfolio

  • Bridl
  • Obdoor
  • Laiqa
  • Rocca Box
  • Plantify
  • City of Cars
  • No-limit-Qr
  • Sync Remote

Platform

  • Artificial Intelligence
  • Blockchain
  • IOT
  • MVP
  • Angular
  • PWA
  • Devops
  • Drupal

Industries

  • Restaurant
  • Healthcare
  • Real estate
  • On-demand
  • Travel
  • Education
  • Fitness
  • Pet Care

Recognized For Excellence

GoodFirms Award
TopDevelopers.co Award
Clutch Leader Award
DesignRush Award
SelectedFirms Award

© 2026 Appic Softwares. All Rights Reserved. |Privacy Policy