Drupal has some handy functions specifically designed for the manipulation of HTML elements.
- Add
{{ kint(attributes) }}
in your theme's node.html.twig. Review the object and its properties and methods. Note thataddClass()
is an available public method.
- Change
<article{{ attributes.addClass(classes) }}>
to<article{{ attributes.addClass(classes).addClass('myclass') }}>
. Observe the new value in kint as well as the new class in your site's markup.
-
Remove all kint() statements from node.html.twig.
-
Copy classy's html.html.twig into your theme.
$ cd MYDRUPAL $ mkdir themes/custom/acme/templates/html $ cp core/themes/classy/templates/layout/html.html.twig themes/custom/acme/templates/html/html.html.twig
-
Clear Cache
-
Above the DOCTYPE declaration and below the comments, add the following code.
{% set myclasses = ['red', 'green', 'blue'] %}
-
Find the line
<body{{ attributes.addClass(body_classes) }}>
and change it to<body{{ attributes.addClass(body_classes).addClass(myclasses) }}>
You should now see classes
red
,green
andblue
attached to the body tag.
Let's create a special body class for the user role.
-
Note that
logged_in
is one of the variables available in html.html.twig according to its comments. -
Use
{{ kint(user) }}
to inspect the user variable in html.html.twig. Search the kint foraccount
. Note that the methodgetAccount()
is public. If we look back at Exercise 8, we see that we can use{{ user.account }}
because of that sweet, sweet Twig magic. -
Use
{{ kint(user.account }}
. Search forroles
. Look at that! Our friends at D.O. also madegetAccount()
public. Now we can do the thing. -
Below
{% set myclasses = ['red', 'green', 'blue'] %}
add
{% if logged_in %}
{% set roles = user.account.roles %}
{% endif %}
- Change the body tag to
<body{{ attributes.addClass(body_classes).addClass(myclasses).addClass(roles) }}>
- Compare the
<body>
tag for logged in and logged out users. What are the results when you remove theif
statement?
- How do I remove a class?
- Where can I find other cool twig functions?
- What happened to preprocess functions and the template.php file?
- Why do we copy our template files from the classy theme?
- How did you know the
user
variable was available? - Why did we do that?
We're getting pretty good at this!. Let's see what Exercise 10 - Twig Filters has to offer...