2

I'm showing the name of the currently logged-in user in header, using \Drupal::currentUser()->getUsername(), but it's showing an already cached page. I know I can disable the cache for a particular page using \Drupal::service('page_cache_kill_switch')->trigger(), but this won't work with the header.html.twig file.

How can I achieve it without affecting the performance?

1
  • 1
    You haven't provided much information about how you're adding the username into your template. But you might be better putting your user content into a block and adding it into a region. That way with the relevant user cache tags/context on your block it will get cached per user – Leigh Jun 20 '19 at 8:09
4

You need a cache context and a cache tag of the user:

$variables['username'] = [
  '#markup' => \Drupal::currentUser()->getUsername(),
  '#cache' => [
    'contexts' => [
      'user',
    ],
    'tags' => [
      'user:' . \Drupal::currentUser()->id(),
    ],
  ],
];

You can add this directly in a preprocess hook, but then the rendered output will vary for each user. For large numbers of users you might want to put this in a lazy builder callback, which will then match the auto-placeholder conditions and can be lazy-loaded through BigPipe without affecting page load performance.

See https://www.drupal.org/docs/8/api/render-api/auto-placeholdering

1
  • 1
    The cache metadata can be specified directly in Twig template. {{ {'#cache': {contexts: ['user'], [tags: 'user:' ~ user.id]} }} – ya.teck Jul 16 '19 at 12:49

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.