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:

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

  • 1
    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 '16 at 16:18
  • Thanks @Rainer - is it fine to mix contexts and tags (e.g. 'node:123') in the same #cache ? – Nic Jun 20 '16 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 '16 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. – Rainer Feike Jun 22 '16 at 16:50

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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