1

I created a search form in my navigation and as it is described in the documentation, I created an search/results.html. And actually it works so far.

Now comes the problem: The results.html extends the "_base.html" and in this file I set the meta properties like this:

{% if entry.seoPageTitle is defined and entry.seoPageTitle != null %}
  {% set metaTitle = entry.seoPageTitle %}
{% else %}
  {% set metaTitle = entry.title %}
{% endif %}

and the HTML:

<title>{{ metaTitle }}</title>

And also this works so far.

But in combination it doesn't work. When I tipe in a Word in my Searchform and click "Search", then it gets "Variable "entry" does not exist". How can I fix it?

1

Yeh this a common problem I've run into as well.

The issue is the entry variable only gets set when Craft is routing to an entry that's created in the CMS. Since you're routing directly to a template, Craft can't populate the variable.

I can think of a couple workarounds:

If your search form page is defined in the CMS, just grab that (or another page):

{% set entry = craft.entries.section('whatever').slug('search').one() %}

Another option is just to modify your code for fallbacks:

{% if entry is defined %}

    {% if entry.seoPageTitle is defined and entry.seoPageTitle != null %}
      {% set metaTitle = entry.seoPageTitle %}
    {% else %}
      {% set metaTitle = entry.title %}
    {% endif %}

{% else %}

    {# set the fallback from a global for example #}
       {% set metaTitle = defaults.metaTitle %}

{% endif %}

That's a lot of code for basically setting variables. What you could do to help clean this up is to use the null-coa­lesc­ing operator or default filter in Twig:


{% if entry is defined %}
      {% set metaTitle = entry.seoPageTitle|default(entry.title) %}
{% else %}
      {# set the fallback from a global called "defaults" as an example #}
      {% set metaTitle = defaults.metaTitle %}
{% endif %}

2
  • Thank you so much! You made my day :) I tried the "Another option" and it works now. Now I try to clean it up with your third proposal.
    – ChuckLean
    Dec 22 '20 at 8:52
  • @ChuckLean You bet. If it worked for you, feel free mark it the accepted answer. Dec 23 '20 at 15:28

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.