4

I would like to cache a variable and compare the cached variable with a parameter from the query string.

Is it possible to somehow cache a variable ?

{% cache using key "cacheId" %}
  {% set id = 1 %}
{% endcache %}
Brad Bell
  • 67,440
  • 6
  • 73
  • 143
Marco Schuler
  • 620
  • 3
  • 13

2 Answers2

5

You can accomplish this by using the set/endset tags to create a variable from the cached output:

{% set finalVariable %}
    {% cache %}
        {# heavy lifting (like queries) here #}
        {# output the contents of your variable here #}
        your output here or {{ yourOutputHere }}
    {% endcache %}
{% endset %}

In the above example the finalVariable will be set to the value of the cached content.

Or, in the case of the code example used in the question, something like this could be used:

{% set id %}{% spaceless %}
    {% cache using key "cacheId" %}
        1
    {% endcache %}
{% endspaceless %}{% endset %}

It's a very basic example that would probably never be used, but the id variable would be set to a string of 1 from the cacheId cache.

Note: The spaceless tags are just used to remove the whitespace.

Aaron Waldon
  • 206
  • 2
  • 2
3

The Twig {% cache %} will only cache HTML output, not variables. You could, however, store the value you want to check against in a cookie or into the browser's local storage.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143