3

I wrote a little plugin that reads some entries (Events) from my events section, orders them in a calendar-like structure and returns them to be displayed in a template. (I couldn't do this twig-only)

Now, I would like to use {% cache %} on the calendar. I know that Craft normally busts the template cache when updating/adding an element if it detects, that those elements were used in a cached template.

Now as I am fetching the elements in my custom plugin with

$criteria = craft()->elements->getCriteria(ElementType::Entry);

I assume, that Craft can't know when to bust the cached output of the plugin.

Is there a way (with the TemplateCacheService for example) to make sure that this cache also gets busted when saving/updating one of my events?

I wonder if I can do this just in twig or if I would have to put a hook before the element gets saved? How does it relate to the cache key?

Any hints, which direction to take?

Thank you,

Robert


Update:

Okay, I'll provide some more details:

My Plugin looks (simplified) like this:

// MyPluginVariable.php: 
public function getMonthWithEvents($month, $year)
{
    ...
    $criteria = craft()->elements->getCriteria(ElementType::Entry);
    $criteria->section = 'events';
    $criteria->date = ['and', '>='.$monthStart, '<='.$monthEnd];
    $eventsInMonth = $criteria->find();

    $month = [];

    // Put events in month array with dates etc....

    return $month;
}

In the twig template, I do this:

// agenda.twig
...

{% cache %}

    {% set month = craft.migrosAgenda.getMonthWithEvents(10, 2016) %}

    {% for day in month %}
        ...
        <div class="day">
            {{ day.date|date('d.M.Y') }}
            {{ day.event.title }}
            {{ day.event.date }}
        </div>
    {% endfor %}

{% endcache %}
3

Hard to know for sure without seeing some plugin code, but my guess is you'll want to use the TemplateCacheService's includeElementInTemplateCaches similar to how BaseTemplate's _includeElementInTemplateCaches does.

  • Thank you. I updated my question with some more details and plugin code. I don't understand yet how I would relate the event elements to that certain cached template part. Do I need to use a special key {% cache key = "xy %} and refer to that in the plugin? Would it also be a easier solution to maybe read the event elements in twig normally with craft.entries() and then pass it to the plugin? – exophunk Aug 18 '16 at 7:06
  • Update: I used the includeElementInTemplateCaches in my plugin as you proposed and it works perfectly. I had to understand the idea, that it is doing this while being "inside" a cache tag and therefor I don't have to relate it to a certain templatecache :) Thank you! – exophunk Aug 18 '16 at 7:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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