How to add a class to a Twig template?

How to add a class to a Twig template?

1. Add a class to the { { attributes }} variable in a Twig template. When looking at any twig template, you will notice an { { attributes }} variable. This is used to add classes, IDs, and other attributes to a piece of content. If you ever need to alter to this variable, you can so by adding a few lines in your yourtheme.theme file:

How to create your own variables in twig?

We can use {% set %} to create our own variables directly in a twig template, without ever needing to touch the `.theme` file. bg_color is the variable name. Can be used like { { attributes.addClass ( bg_color ) }} or class = “ { { bg_color }}” ‘Color’~ is being prepended to the value of the background color field (example: color-black)

When to leave the region name empty in twig?

If the region_name (this is an existing twig variable) is featured middle, set the variable class to “full-width”. Otherwise, leave the variable empty. 6. Rendering a Block or View in Twig

How to check if a field is populated in twig?

In Twig, there are a number of ways to check if a variable is defined or not. Since fields are used like variables in a template, the approach is similar. In order to accurately check if a field is populated, you need to use a combination of filters and loops: Example: If the node has an image, display in a two column layout.

~ is a Twig operator that concatenate two strings together region: the region variable. It will be replaced with the actual region (e.g. block) |: A pipe that separates a variable ( region) from a filter ( clean_class) clean_class: a filter that will remove invalid characters from HTML classes

How to load CSS / SCSS / JS / HTML from twig?

Once this is done, add the following to your Twig file (i.e. particle.html.twig): If the twig file you are using is for a particle, ensure it is being used on your Outline > Layout and you have cleared your Gantry cache. Load the page and you should see your SCSS code compiled into CSS.

Why do you add CSS classes to templates?

Adding CSS classes to templates allows you to target templates or parts of the template in your CSS files. For example, if you want a different background colour per content type, then you need a way to identify each content type with a CSS selector.

What does ~ do in Twig template in Drupal?

Let’s break this down: ~ is a Twig operator that concatenate two strings together region: the region variable. It will be replaced with the actual region (e.g. block) |: A pipe that separates a variable ( region) from a filter ( clean_class)