I have a long if/else block within a for loop in my template and I wanted to cache all of it (it loops over a Matrix field, checking for different block types on each row and outputs the correct code as needed). However, in one of the ifelse blocks, I have a statement with a RAND parameter that I don't want cached. Something like this:
{% for block in entry.sidebar %}
{% if block.type == "someType" %}
...Presentiaon code
{% elseif block.type == "someType" %}
...Presentiaon code
{% elseif block.type == "someType" %}
{% set randomEntry = craft.entries.section("testimonials").order('RAND()').first() %}
{% endif %}
{% endfor %}
My challenge is trying to find a way to cache this long block but still let the RAND work. My solution was to try to put the matrix field into a variable, cache that variable and then iterate over the variable's data (the thinking here that the variable has all the process-intensive DB queries). Something like this:
{% cache %}
{% set myField = entry.myMatrixField %}
{% endcache %}
{% for block in myField %}
{% if block.type == "someType" %}
...Presentiaon code
{% elseif block.type == "someType" %}
...Presentiaon code
{% elseif block.type == "someType" %}
{% set randomEntry = craft.entries.section("testimonials").order('RAND()').first() %}
{% endif %}
{% endfor %}
However, this fails after the template has been cached with an error that the 'myField' variable does not exist. So I'm thinking I can't do this?
Is there another way I could cache this? I considered breaking up the ifelse blocks into separate if/endif clauses and caching each except the one with the RAND paramater in it but I'm thinking that won't improve performance much if the for loop still has to run outside of it uncached.