3

I have a multilingual site with custom blocks in the right-hand menu - the content of which is generated dynamically through the build() function of BlockBase and which changes depending on the interface language. I want to cache these once per language. Elsewhere I've used:

public function build() {
 $node = \Drupal::routeMatch()->getParameter('node');
 return array(
  '#theme' => 'my_template',
   ....
  '#cache' => [
    'tags' => [
      'node:' . $node->getId()
    ],
  ],
);

}

I've gone with this approach, which appears to work, although I'm not sure how to test that it isn't still processing templates on every call:

public function build() {
 return array(
  '#theme' => 'my_template',
   ....
  '#cache' => [
    'tags' => [
      'language:' . \Drupal::languageManager()->getCurrentLanguage()->getId()
    ],
  ],
);

}

Is this the correct way to do it? I could find examples of the node: prefix in the docs, but nothing about language:

1 Answer 1

7

You should use the languages context, don't use tags here.

Like this: '#cache' => ['contexts' => ['languages:language_interface']],

You'll find more here: https://www.drupal.org/developing/api/8/cache/contexts

4
  • 4
    Correct answer, but note that the interface language is already a default cache context that is applied to anything. So it should already do that without having to specifiy anything. If it doesn't work then you have a different problem.
    – Berdir
    Jun 20, 2016 at 16:18
  • 1
    Thanks @Rainer - is it fine to mix contexts and tags (e.g. 'node:123') in the same #cache ?
    – Nic
    Jun 20, 2016 at 17:56
  • Yes, it's fine. The cache array is better described as the invalidate-cache-when array. That means the cache will be invalidated when one of the contexts changes or one of the tags is invalidated.
    – Eyal
    Jun 21, 2016 at 19:58
  • Yes, Eyal is right. And the third caching mechanism is "max-age". You may mix all three cache keys (tags, contexts, max-age). The cache is invalid if at least one of them is invalid. Jun 22, 2016 at 16:50

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.