How To Get Started With Twig With Drupal 9?

How To Get Started With Twig With Drupal 9?

Twig With Drupal 9

Twig tweak module saves Drupal writers a lot of time when they are working with advanced twig templates. It has a number of features and filters that developers can use to make their work easier. Developers can also write code that is easy to read and understand because it is written well. For quick and easy Drupal development, you should use the Twig edit module in Drupal 9.

EOL is now here for Drupal 8. The time has come to switch to Drupal 9. But if you are still trying to figure out how to make a custom module in Drupal 8, these methods will still work. 

How to put the Twig Tweak Module in place

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

composer require drupal/twig_tweak

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

Using 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) }}

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%>

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’}) }} 

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.

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) }}

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.

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 ) }}

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) }}

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) }} 

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 ….) }}

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’) }}

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

Image

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

Sentence structure:

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

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 a responsive style.

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 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 twig tweak, we can get the following numbers. 

Sentence structure:

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

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 composer. 

Sentence structure:

{{ drupal_dump(var) }} 

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) }}

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) }}

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) }}

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) }}

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!”.

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) }}

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: An 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.

Through Filter

This adds more items to the list. It also gives back an array with the 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, to 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.

Get Free Consultation Now!


    Contact Us

    Consult us today to develop your application.

      Get in touch with us


      Skype Whatsapp Gmail Phone