Trouble adding conditional to page-title.html.twig I am building my first D8 theme and I am new to Twig. I am trying to add a class to the h1 title tag on the home by editing page-title.html.twig, but I can't get it to take. Here is my code

{% set body_class = '' %}
{% if title == 'Welcome to My Website' %}
    {% set body_class = 'home-page-title' %}
{% endif %}

{{ title_prefix }}
    &lt;h1{{ title_attributes.addClass(body_class) }}&gt;{{ title }}&lt;/h1&gt;
{{ title_suffix }}
You're doing it wrong. The method you are using is not consistent if you change the page title to something else, or use another page as your landing page.

There are two ways to solve this:

The long way, using hook_preprocess_html()

Instead of this, I recommend targeting the &lt;h1&gt; tag through a body selector, and add there a special class for front page through hook_preprocess_html(). This is a cleaner solution, and you can target other elements as well.

This code would go to your YOUR_THEME.theme file:

function YOUR_THEME_preprocess_html(&amp;$variables) {
  // Add a custom class determining if we're on the front page.
  if (\Drupal::service('path.matcher')-&gt;isFrontPage()) {
    $variables['attributes']['class'][] = 'front';
  }
  else {
    $variables['attributes']['class'][] = 'not-front';
  }
}


In your html.html.twig file you need to have:

&lt;body{{ attributes }}&gt;


Then in your CSS file, you would use:

body.front h1.page-title {
  /* Your styles. */
}


The short way, using only twig - by 4k4

The root_path variable provided to you by template_preprocess_html() will be set to FALSE when you are on the front page. This means that you can use it as condition argument, and give different class to the body element.

Here's an example:

&lt;body{{ attributes.addClass(root_path ? 'not-front' : 'front') }}&gt;


Hope this helps.