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 %}

2 Answers 2


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" %}
    {% 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.

  • You also need to use {%- instead of {% to remove whitespace inbetween the Twig tags.
    – carlcs
    Commented Apr 14, 2016 at 7:54

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.