8

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 %}
JMKelley
  • 1,384
  • 10
  • 27

9 Answers9

9

Our homepage is set via Craft's recommendation:

You can designate any one entry as a site’s homepage using a special home URI.

Since the homepage is an entry, it will always have an entry object with a uri, so I can use a simple one-liner like:

{% set isHomepage = entry is defined and entry.uri == "__home__" ? true : false %}

Tammy Shipps
  • 389
  • 2
  • 6
7

I'd rather:

{% if entry.uri == "__home__" %}

{% endif %}
Urs
  • 639
  • 4
  • 13
  • this only works if the page is pulling from an entry, otherwise: Variable "entry" does not exist. – Leo Leoncio Sep 07 '20 at 18:25
  • 1
    @LeoLeoncio The homepage is an entry, so if you are checking if whatever you're on is the homepage or not, you can assume false if there's no entry object. Otherwise, it's a custom setup and answering would require more info. – Tammy Shipps Nov 29 '20 at 18:36
7

The best option for Craft 3 and 4 is probably entry.isHomepage, i.e.

{% if entry is defined and entry.isHomepage %}
   This is the homepage
{% endif %}
Mats Mikkel Rummelhoff
  • 22,361
  • 3
  • 38
  • 69
3

This works in Craft 3

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

{% if url == "/" %}
   homepage
{% endif %}
triplethreat23
  • 549
  • 2
  • 15
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.

James White
  • 1,151
  • 6
  • 19
2

Another option for you. Check for the presence of a url segment.

{% if not craft.app.request.segment(1) %}
    This is the homepage
{% endif %}
foamcow
  • 2,019
  • 9
  • 20
2

This works nicely and limits error possiblities:

{% if craft.app.urlManager.matchedElement and craft.app.urlManager.matchedElement.uri == '__home__' %}
    Show on homepage
{% endif %}
Dario Zadro
  • 173
  • 7
1

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

{% if craft.app.request.url == '/' or craft.app.request.url == '/' ~ craft.app.language %}
Leo Leoncio
  • 473
  • 3
  • 9
1

My current approach

{% if entry.isHomepage|default %}
Homepage
{% endif %}

Tested in Craft4

Leevi Graham
  • 433
  • 2
  • 6