Hello everyone, welcome back to techbrushup. In this tutorial, we will learn about How do you add a class to a Twig template in Drupal 8 +.
Adding CSS classes to templates allows you to target templates or corridor of the template in your CSS lines.
For illustration, if you want a different background colour per content type, also you need a way to identify each content type with a CSS chooser. By dereliction the knot template includes a class for each content type, making it easy for you to target each bone . You ’ll see this in action latterly on in this tutorial. You'll also learn how to produce your own classes.
- Adding a single class
-
To add a class, pass in the class name as an argument to the attributes.addClass() function.
<div {{ attributes.addClass('classname') }}> </div>
- Adding multiple classes
-
To add multiple classes to an element, produce an array with all of the class names. To produce an array in Twig, use the set label followed by the name of the array.
{% set classes = [ 'content', 'node', 'custom', ] %}
<div {{ attributes.addClass(classes) }}> </div>
- Classes are added with existing classes if any
- If there are any classes that already exist, the new classes will be combined. Thus, all the classes will be included in the element.
- Removing a class
-
You have the option to remove one of the existing classes. To do that, you can use the attributes.removeClass() function.
<div {{ attributes.addClass(classes).removeClass('node') }}> </div>
- Two practical examples.
- In your code editor, navigate to the templates in the Classy theme.(core/themes/classy/templates).
- Single class
-
Open field/time.html.twig. This is an example of a single class being added to the time element.
<time{{ attributes.addClass('datetime') }}>{{ text }}</time>
- Multiple class array
-
Open up layout/region.html. The classes array
{% set classes = [ 'region', 'region-' ~ region|clean_class, ] %}
'region-' ~ region|clean_class,
- region-' a simple sting
- ~ The Twig operator concatenates two strings together.
- region: The region is variable. The actual region (e.g. block) will be replaced.
- |: A pipe that distinguishes a variable (region) from a filter (clean_class).
- clean_class: A filter that will eliminate any invalid characters from HTML classes
- Node class
-
The last example consists of the classes added to the article element in the node template.
Go to content/node.html.twig and open it. Another example of multiple classes can be found here.
set classes = [ 'node', 'node--type-' ~ node.bundle|clean_class, node.isPromoted() ? 'node--promoted', node.isSticky() ? 'node--sticky', not node.isPublished() ? 'node--unpublished', view_mode ? 'node--view-mode-' ~ view_mode|clean_class, ] %}
node-- type-' ~ nodebundle|clean_class,
node--type-article
node.isPromoted() ? 'node--promoted',
not node.isPublished() ? 'node--unpublished',