2

I have a template element that is used on almost every page of the site. I would like to cache that element globally, except on one particular page I would like it to just be a normal cache based on the page URL.

The current code I'm using is below, which is not working as intended. The global cache is still working on entry id 126.

{% cache globally using key 'entry_' ~ entry.id ~ '_elements' unless entry is not defined or entry.id == '126' %}

What would be the best way to make that functionality work without slowing down any other pages? Thanks!

4
  • Just as a test try this on the entry 126 page: {% cache globally using key 'entry_' ~ entry.id ~ '_elements' unless entry.id == '126' %}
    – Brad Bell
    May 3, 2017 at 19:17
  • Hey @BradBell, thanks for the response. Tried the test and still seeing the same caching issues.
    – dpayne
    May 3, 2017 at 20:26
  • Are you sure it's entry 126? May 4, 2017 at 18:22
  • @RitterKnight Yes. I also tried using entry.title and had the same problem. Still need to try the solution below and will update as appropriate but looks like that should work.
    – dpayne
    May 4, 2017 at 20:20

2 Answers 2

3

You could add a variable like globalCacheDisabled and {% cache globally using key 'entry_' ~ entry.id ~ '_elements' unless globalCacheDisabled %} and use a {% set globalCacheDisabled = entry.disableGlobalCache %} on the given page template.

On Craft's side I'd use a Lightswitch field on the entry with handle disableGlobalCache, which is disabled by default which you can then activate on the given entry/ies.

This makes you prone to changing id's and differences across environments. (While testing make sure to purge the cache)

2

So the caching issue I was having was on our blog overview page - a page on which you can do filtering to show entries of a certain category. Whenever someone would do a filter - the header would remain cached, when it should have updated to reflect the filter.

Anyway, I think in most cases @lazy pirate's solution would have worked but it wasn't working for me - possibly because the filtering was making it so Craft wasn't viewing the page as one single entry when a filter was run?

The solution I came to that worked for me was this:

{% cache globally using key 'entry_' ~ entry.id ~ '_elements' unless entry is not defined or craft.request.segment(1) == 'blog' %}

That worked because 'blog' is always in the same position in the URL, even when filtered. Hope that helps someone!

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.