0

I have a search results page set up like this:

{% set searchResults = craft.entries(queryParams) %}
{% paginate searchResults as pageInfo, pageEntries %}

{% if pageEntries|length %}
  {% for yacht in pageEntries %}
    {% set prevEntry = item.prev %}
    {% set nextEntry = item.next %}
    <a href="{{ item.url }}
    {% if nextEntry or prevEntry %}?{%endif%}
    {% if nextEntry %}next={{nextEntry}}{%endif%}
    {% if prevEntry and nextEntry %}&{% endif %}
    {% if prevEntry %}prev={{prevEntry}}{%endif%}"
    >Link</a>
  {% endfor %}
{% endif %}

That works fine except that it outputs the entry title of the next and previous entries. If I do nextEntry.url or prevEntry.url (or slug) I get:

Impossible to access an attribute ("url") on a null variable.

Why is that?

1 Answer 1

1

You should check if there is a next and previous element. Most likely you reach the end or the beginning of your list and there is no element thus these variables are null so you receive an exception when you try to grab attributes from null

6
  • Except that entry titles are being returned, just not url or slug.
    – Tyssen
    Commented Jul 9, 2018 at 6:13
  • What do you do to display them? Only {{ nextEntry }}? Commented Jul 9, 2018 at 6:14
  • If I do {{ nextEntry }} I get output like Entry Title. If I do {{ nextEntry.url }} or {{ nextEntry.slug }} I want to get entry-title but instead get the error.
    – Tyssen
    Commented Jul 9, 2018 at 6:23
  • Because {{ nextEntry }} will trigger the objects __toString function. You don't actually access the real title attribute as with {{ nextEntry.title }}. Without that function you would receive an object can not converted to string Exception. You need to check if the variable is null or not. Short syntax would be {{ nextEntry.url ?? '' }} Commented Jul 9, 2018 at 6:25
  • Sorry, you've lost me. If I do {% set prevEntry = item.prev.slug %} and check if prevEntry exists, I get the same type of error. If item.prev produces something, then surely the slug wouldn't be null because it's returning information about a valid entry that exists with a slug.
    – Tyssen
    Commented Jul 9, 2018 at 6:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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