1

How does the Craft CMS cache work? I want to show a certain message if the server date is between x and y. Can I do this by using an Twig if/else statement or is this cached?

My code is like this:

{% set now = "now"|date("U") %}

{% set tournamentDates = [
    1536323400,
    1536409800,
    1536971400,
    1537650000,
    1537736400
]
%}

{% for tournamentTime in tournamentDates %}

  <!-- {{ tournamentTime|date("d-m-y H:i:s")}} -->

  {% if ( now > tournamentTime ) and ( now < tournamentTime + 43200 ) %}

    TOURNAMENT IS LIVE

  {% endif %}

{% endfor %}

2 Answers 2

1

Yes, you can do that in Twig. Twig compiles down to PHP, which gets executed for every request. Craft doesn't do any inherent caching, you have to explicitly ask it to cache things via the {% cache %} tag, so the example you posted would work fine.

If you want to learn more about the {% cache %} tag, check out The Craft {% cache %} Tag In-Depth

1

Using the cache tag, you can control when the cache will expire.

If I understand correctly, the check you are doing will have a different result on a daily basis. You can ask a piece of content to be cached until the end of the day. The first request of the next day will automatically clear the cache and the content will be generated again.

You can define the cache expiration time like this:

{# The cache should expire at the beginning of each day #}
{% set cacheExpirationTime = now|date_modify('+1 day')|date('Y-m-d 00:00')|date('c') %}

You can then use this variable in the cache tag:

{% cache until cacheExpirationTime %}
    {# Heavy calculations here #}
{% endcache %}

Please note that if you fetch some content from Craft within the cache tag and this content gets modified, the cache will automatically be cleared before the expiration time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.