2

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 }}
    <h1{{ title_attributes.addClass(body_class) }}>{{ title }}</h1>
{{ title_suffix }}
2

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 <h1> 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(&$variables) {
  // Add a custom class determining if we're on the front page.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $variables['attributes']['class'][] = 'front';
  }
  else {
    $variables['attributes']['class'][] = 'not-front';
  }
}

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

<body{{ attributes }}>

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:

<body{{ attributes.addClass(root_path ? 'not-front' : 'front') }}>

Hope this helps.

  • Perfect solution, you can even make it shorter or doing it all in twig by using the variable root_path which is FALSE if the page is front (see template_preprocess_html() in theme.inc) – 4k4 Mar 24 '16 at 20:18
  • Ha! That's a good one - will include it in the answer. – Aram Boyajyan Mar 24 '16 at 20:26
  • Thanks! Both of these work great! I'm going with the short way. – JOakland Mar 24 '16 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.