Is it possible to have multiple cache entries depe

2019-09-15 06:42发布

问题:

I have a complex variable {{course_type.title[language] | nl2br}} in my custom block template. language is the current sites language but the content is only delivered in the language of the time, when the cache was build.

I do have languages in my render array and it works for {% trans %} commands in the twig template:

 return array(
    '#theme' => 'block__vt_course_offer',
    '#data' => $courseData,
    '#cache' => [
        'contexts' => ['languages'],
        'tags' => $cacheTags,
    ]
);

Is there a way to get Drupal to handle multiple cache entries based on the current language of the page?

Thx a lot!
Andreas

回答1:

So we found a solution for this - we extracted the different parts into sub render arrays and dissabled the cache only for them. Important is, that the access to data[$language] is happening in the main module, not in the template.

      foreach ($courses as &$courseType) {
            $courseType['d_url'] = $dcm->getCourseUrl($courseType['id']);

            $courseType['output'] =  array(
                '#theme' => 'block__vt_course_offer_item',
                '#data' => [
                  'id' => $courseType['id'],
                  'image' => $courseType['image'],
                  'duration' => $courseType['duration'],
                  'price' => $courseType['price'],
                  'd_url' => $courseType['d_url'],
                  'title' => $courseType['title'][$language],
                  'short_description' => $courseType['short_description'][$language],
                ],
                '#cache' => [
                  'disabled' => TRUE,
                  'contexts' => ['languages'],
                  'tags' => ['courseType:' . $courseData['data']['course'][0]['id']],
                ]
            );

Then we can use it in the twig as:

 {% for course_type in courses|slice(i * 4, (i+1) * 4) %}
      {{ course_type.output }}
 {% endfor %}

In a nutshell it boils down to the template usage of {{variable.preset_language_value}} instead of {{variable.value[language]}}