5

I'm working on a english/spanish site that includes a language switcher link in the site footer.

The code for the switcher grabs the currently displayed entry, checks whether a corresponding entry exists in the other locale. If it does exist, the clicking the switcher will link to the corresponding entry. If not, you'll land on the other locale's homepage. If we're already on the homepage, just redirect to the homepage.

The code, simplified, looks like this:

{% if entry.sectionId == 1 %} // The homepage

  // Redirect to homepage

{% else %}

  // Do some checking into whether there's a corresponding entry, etc.

{% endif %}

The problem:

I have some pages on my site that aren't entries, and on these pages, I get a template error telling me that Variable "entry" does not exist

I tried rewriting this code so I'd check if that variable exists first:

{% if entry|length %}

 // Do the previous code

{% endif %}

But this gives me the same error. How can I write this logic so I don't have to rely on the entry variable existing or not, which should presumably avoid the error.

Thanks!

6

You are close, instead of checking entry|length, you can do {% if entry is defined %}

{% if entry is defined and entry.sectionId == 1 %}

So if I am understanding correctly, the full code will be:

{% if entry is defined and entry.sectionId == 1 %}

    //  Redirect to homepage

{% else %}

    // Do some checking into whether there's a corresponding entry, etc.

{% endif %}
|improve this answer|||||
  • That's great Jamie. Exactly what I needed. Thanks! – Adam Snetman Oct 10 '14 at 18:35
  • @AdamSnetman glad to help! – Jamie Wade Oct 10 '14 at 18:41

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.