I've spent the best part of the last day or two trying to implement lazy_builder (as seen in this brilliant tutorial https://github.com/joachim-n/drupalcon-europe-2020-lazy-builders).
However, rather than with a block or page render. I'd like to implement the lazy_builder into hook_tokens() and make the $replacements value dynamic so that it uses the lazy_builder.
We have a value saved to session that we use as the value of a token (so it back be used across the site).
$session = \Drupal::request()->getSession();
$session->get('my_value');
I've tried setting $bubbleable_metadata with both addCacheContexts and addCacheableDependency
$bubbleable_metadata->addCacheContexts(['session']);
&
$session = \Drupal::request()->getSession();
$bubbleable_metadata->addCacheableDependency($session);
However both these options make the page UNCACHABLE.
I'd like to keep the page a cache HIT, but load in the token value via lazy_builder.
My question is, is there anyway to leverage lazy_builder, in the token replacement?
/**
* Implements hook_tokens().
*/
function mymodule_tokens($type, $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
$replacements = array();
if ($type == 'my_token') {
foreach ($tokens as $name => $original) {
// Find the desired token by name
switch ($name) {
case 'my_token':
$session = \Drupal::request()->getSession();
//make the below use lazy_builder
$replacements[$original] = $session->get('tracking');
break;
}
}
}
// Return the replacements.
return $replacements;
}
#lazy_builder
is used in render arrays. It's not clear how you would use it to change the value returned from a token.hook_tokens()
could be invoked for every page. The code shown in the question doesn't make clear for which page it would be used or called.