1

Caching is hard.

I want to delete the cache when a news entry hits it's expiryDate. So I wrote

{% set newsExpiration = craft.entries.section('news').first()%}

{% cache until newsExpiration.expiryDate  %}
   Bla
{% endcache %}

Now the news entry has expired and no news is present so there is an error:

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

I then wanted to write a conditional to see if newsExpiration is defined.

{% if newsExpiration is defined %}
   {% cache until newsExpiration.expiryDate  %}
{% else %}
   {% cache %}
{% endif %}

But that also throws an error because Twig is expecting a closing tag to the cache.

Unexpected "else" tag (expecting closing tag for the "cache" tag defined near line xy).

I there a proper way to define the cache tag including both present and absent entries without query conditionals?

2

Caching is hard.

https://twitter.com/codinghorror/status/506010907021828096

Something like this should work.

{% if newsExpiration is defined %}
    {% cache until newsExpiration.expiryDate  %}
        ...
    {% endcache %}
{% else %}
    {% cache %}
        ...
    {% endcache %}
{% endif %}

You'd probably want to use an include for the body of the two cache tags to keep things DRY.

| 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.