How do I check if the current page is the front page from node.html.twig?

GIJO picture GIJO · Apr 28, 2016 · Viewed 8.3k times · Source

I'm currently trying to integrate a website with Drupal 8. My front page is just a bit different than the other pages and I need to check in node.html.twig if the current page is the front page to add a "div". The variable "is_front" is working fine on page.html.twig but it seems not to be available on node.html.twig. How could I fix this problem?

Answer

Cyclonecode picture Cyclonecode · Apr 27, 2017

You can also add this variable by using a preprocess hook. The following code will add the is_front variable so it can be used in the html.html.twig template:

// Adds the is_front variable to html.html.twig template.
function mytheme_preprocess_html(&$variables) {
  $variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
}

Then inside the twig template you could check the variable like so:

{% if is_front %}
THIS IS THE FRONTPAGE
{% endif %}