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 %}
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityI 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 %}
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.
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.
{%-
instead of {%
to remove whitespace inbetween the Twig tags.
– carlcs
Apr 14 '16 at 7:54