function hook_tokens_alter

Same name in other branches
  1. 7.x modules/system/system.api.php \hook_tokens_alter()
  2. 9 core/lib/Drupal/Core/Utility/token.api.php \hook_tokens_alter()
  3. 8.9.x core/lib/Drupal/Core/Utility/token.api.php \hook_tokens_alter()
  4. 11.x core/lib/Drupal/Core/Utility/token.api.php \hook_tokens_alter()

Alter replacement values for placeholder tokens.

Parameters

$replacements: An associative array of replacements returned by hook_tokens().

$context: The context in which hook_tokens() was called. An associative array with the following keys, which have the same meaning as the corresponding parameters of hook_tokens():

  • 'type'
  • 'tokens'
  • 'data'
  • 'options'

\Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata: The bubbleable metadata. In case you alter an existing token based upon a data source that isn't in $context['data'], you must add that dependency to $bubbleable_metadata.

See also

hook_tokens()

Related topics

1 invocation of hook_tokens_alter()
Token::generate in core/lib/Drupal/Core/Utility/Token.php
Generates replacement values for a list of tokens.

File

core/lib/Drupal/Core/Utility/token.api.php, line 151

Code

function hook_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
    if ($context['type'] == 'node' && !empty($context['data']['node'])) {
        $node = $context['data']['node'];
        // Alter the [node:title] token, and replace it with the rendered content
        // of a field (field_title).
        if (isset($context['tokens']['title'])) {
            $title = $node->field_title
                ->view('default');
            $replacements[$context['tokens']['title']] = \Drupal::service('renderer')->render($title);
        }
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.