2

I'm trying to run a check within my _layout.html' to remove the navigation bar if the user is on the homepage. I've tried with the following code below, but browsing to a page which is theindex.html` of a Channel breaks the code with the following error:

Variable "entry" does not exist.

This is the code within my _layout.html

{% set handle = entry.section.handle %}
{% if handle == 'homepage' %}
{% else %}
  {% if not craft.app.user.isGuest %}
      {% set users = craft.users %}
      {% include '_navigation'%}
    {% else %}
  {% endif %}
{% endif %}
1

This works in Craft 3

{% set url = craft.app.request.url %}

{% if url == "/" %}
   homepage
{% endif %}
| improve this answer | |
  • It doesn't work if the user comes to the page via something like Facebook, which would add a /?fbclid=XXXXX parameter to the end of the URL – Rob Hodges Jul 30 at 11:09
  • I've gone with: {% if not craft.app.request.segments|length %} – Rob Hodges Jul 30 at 11:17
3

I'd rather:

{% if entry.uri == "__home__" %}
  🏠
{% endif %}
| improve this answer | |
  • this only works if the page is pulling from an entry, otherwise: Variable "entry" does not exist. – Leo Leoncio Sep 7 at 18:25
2

To prevent a Twig exception, you may wish to use entry is defined to catch this error.

https://twig.symfony.com/doc/2.x/tests/defined.html

Another way to detect the homepage would be looking at the request with craft.app.request, something like craft.app.request.pathInfo, if it equals /, then you've got your condition.

| improve this answer | |
1

My site is localized, so I ended up doing...

{% if craft.app.request.url == '/' or craft.app.request.url == '/' ~ craft.app.language %}
| improve this answer | |

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.