The documentation for Token::replace() says:
* To ensure that the metadata associated with the token replacements gets
* attached to the same render array that contains the token-replaced text,
* callers of this method are encouraged to pass in a BubbleableMetadata
* object and apply it to the corresponding render array. For example:
* @code
* $bubbleable_metadata = new BubbleableMetadata();
* $build['#markup'] = $token_service->replace('Tokens: [node:nid] [current-user:uid]', ['node' => $node], [], $bubbleable_metadata);
* $bubbleable_metadata->applyTo($build);
* @endcode
The call to Token::replace() should do this and set the metadata on the returned build array.
Furthermore, if the result of the token replacement means that the rendered field item is uncacheable (because it depends on the user or the session), then a lazy builder should be used to prevent the whole page from being uncacheable.
Comments
Comment #2
joachim commentedComment #3
joachim commentedHere's a patch.
Comment #4
sophie.skRerolled the patch against 2.0.0. Hope I got everything in it...
Comment #5
mangy.fox commentedLooks like the lazy builder isn't using the langcode passed in, so the rendered output is always in the default language.
Comment #6
mangy.fox commentedFinally got back around to this. Updated the patch to make sure the entity is in the correct language in the lazy loader.
Comment #7
mangy.fox commentedAdded TrustedCallbackInterface for Drupal 9 compliance.
Comment #8
mangy.fox commentedUpdated patch for 2.1.x
Comment #9
mangy.fox commentedAnd another with latest changes.