Token Replacement via Lazy_builder 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()-&gt;getSession();
$session-&gt;get('my_value');

I've tried setting $bubbleable_metadata with both addCacheContexts and addCacheableDependency
$bubbleable_metadata-&gt;addCacheContexts(['session']);

&amp;
$session = \Drupal::request()-&gt;getSession();
$bubbleable_metadata-&gt;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 =&gt; $original) {
      // Find the desired token by name
      switch ($name) {
        case 'my_token':
          $session = \Drupal::request()-&gt;getSession();
          //make the below use lazy_builder
          $replacements[$original] = $session-&gt;get('tracking');
          break;
      }
    }
  }
  // Return the replacements.
  return $replacements;
}
This answer might be helpful. In your case you could try to bubble up the attachment from the token itself:
$replacements[$original] = '&lt;my-placeholder&gt;';

$bubbleable_metadata-&gt;addAttachments([
  'placeholders' =&gt; [
    '&lt;my-placeholder&gt;' =&gt; [
      '#lazy_builder' =&gt; ['\Drupal\mytheme\MythemeLazyBuilders::replaceUid', []],
    ],
  ],
]);

You not really need the Drupal token system, you can attach placeholders almost everywhere in the rendering process, but for some cases this could be a convenient way to make a lazy builder available.