6

How can I omit a certain tag from being cached?

I have a large page with a fair few queries but halfway down I am loading in a Freeform Form field which cannot be cached. But I'd like all of the content below it to be..

1 Answer 1

5

Unfortunately, the vanilla {% cache %} tag doesn't have a way to escape or ignore certain content.

The obvious workaround is to have more than one {% cache %} tag, where the content that shouldn't be cached sits between/outside those tags.

If you can't do that, another option is to use output buffering and injection. Basically, you cache whatever you need to cache, but {% set %} the output to a variable, rather than rendering it immediately. The important bit: Inside the content that you cache, you put some sort of placeholder value where you want the un-cached content to render. This placeholder can be whatever you want, but make it something that isn't likely to also appear in the actual content (e.g. "%%%foobarbaz%%%"). Then, {% set %} the un-cached content to a variable also – and finally, when you print the cached content, you use the |replace filter to replace the placeholder value in the cached content with the variable containing the un-cached content. Something like this:

{# Set the cached content to a variable #}
{% set cachedContent %}
    {% cache globally using key craft.request.path %}

        {# A bunch of taxing queries here #}
        <p>I am content.</p>

        {# Injection point for un-cached data #}
        %%%foobarbaz%%%

        <p>I am more content.</p>

    {% endcache %}
{% endset %}

{# Set the uncached content to a variable #}
{% set uncachedContent %}
    <p>I am some content that never is cached wooooo</p>
{% endset %}

{# Print the whole thing #}
{{ cachedContent|replace('%%%foobarbaz%%%', uncachedContent)|raw }}

Finally, there's a plugin which may work for you.

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.