Blogs | Srijan

Drupal8 Theming: Part 2

Written by Sanjay Rohila | May 1, 2015 7:00:00 AM

{{ title }} {% endif %}
{# for loop. #}
{% for article in articles %}
{{ article.title }}
{% endfor %}

Other than these basic things, there is a new feature called Filters in templates.

Filters

Some of the frequently used filters are:

addClass:

We can add new class to an element as:

without:

Print whole variable except child element given as argument, so that we can use them later. Eg. {{ content|without('links') }} and use later as {{ content.links }}. This filter creates a copy of the renderable array and removes child elements by key specified through arguments passed to the filter. The copy can be printed without these elements and specific elements can be used later.

passthrough & placeholder:

To pass-through a variable (!) or use as a placeholder (%), the passthrough or placeholder filters are used.

{% trans %}Submitted on {{ date|passthrough }}{% endtrans %}

Striptags:

Striptags removes all HTML tags from the variable.

{{ title|striptags }}

Clean_Class:

The clean_class filter prepares a string to be used as a valid HTML class name. When adding classes dynamically for any value, use clean_class.

clean_id:

The clean_id (same as clean_class) filter prepares a string to be used as a valid HTML ID.

safe_join:

The safe_join filter joins several strings together with a supplied separator.

{{ tags|safe_join(", ") }}

Spaceless:

The {% spaceless %} tag is helpful for removing all non-text whitespace between several tags and statements.

{% spaceless %} {% if block.title %}

    {{ block.title }}

{% endif %} {% endspaceless %}

Compiled markup will be without extra indentation:

{{ block.title }}

Debugging:

Here is a doc https://www.drupal.org/node/1906392 about how to enable debugging in Twig templates. We can also dump variables in Twig templates.

So, these are the things which are different in the new system (template files). There are lots of changes still going on. Some of these can be changed later, but most of them are freezed.

References:

 

Template Files: https://www.drupal.org/node/1918824

Debugging Twig: https://www.drupal.org/node/1906392

Twig Filters  : https://www.drupal.org/node/2357633

 

Here's the first article in this series: Drupal8 Theming: Part 1 

{% endraw}