3

This question already has an answer here:

The following method not returning any value (true or false). \Drupal::service('path.matcher')->isFrontPage();

How to check if the page is front or not?

marked as duplicate by leymannx, No Sssweat, kiamlaluno Aug 3 '18 at 20:54

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Your snippet should actually just give you what you want. Maybe you need to wrap it with a try&catch, see drupal.stackexchange.com/a/204203/15055. Or you maybe need some cache buster strategy as suggested by @Andy in the comments to @Kevin's answer below. Where exactly do you call that snippet from? – leymannx Aug 3 '18 at 19:02
  • The line you are showing is correct, but there could be errors in the rest of the code. Since you aren't showing the rest of the code, we cannot tell you what is wrong, except that it is not the line you are showing, as the answers for the other question make clear. – kiamlaluno Aug 3 '18 at 20:55
  • @kiamlaluno I am trying to use it in .module file . I am using it inside hook_page_attachments. For debugging purpose i am using die() statement on next line . $is_front = \Drupal::service('path.matcher')->isFrontPage(); //print($is_front); die(); – Aditya Joshi Aug 6 '18 at 19:43
10

This is indeed a way to check if it is the front page and should return a value if you check the method code.

I am using it in a few preprocess hooks:

$variables['is_front'] = \Drupal::service('path.matcher')->isFrontPage();
  • 2
    If you do that, I think the url.path.is_front cache context should be added. – Andy Aug 3 '18 at 18:21
  • @Andy – Interested in how that would like like then I am. – leymannx Aug 3 '18 at 18:53
  • 1
    @leymannx I believe in a theme preprocess you can set #cache and #attached on the variables array, see ThemeManager::render() - if that answers your Q? ie $variables['#cache']['contexts'][] = 'url.path.is_front'; – Andy Aug 3 '18 at 19:06
  • @Andy – Yeah, thanks for sharing! Will keep it in my valuable little Drupal gems box :) – leymannx Aug 3 '18 at 19:11
3
  • Twig : You can use {% if is_front %}. here is an example page.html.twig
  • PHP: \Drupal::service('path.matcher')->isFrontPage();

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