function hook_tokens

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

Provide replacement values for placeholder tokens.

This hook is invoked when someone calls \Drupal\Core\Utility\Token::replace(). That function first scans the text for [type:token] patterns, and splits the needed tokens into groups by type. Then hook_tokens() is invoked on each token-type group, allowing your module to respond by providing replacement text for any of the tokens in the group that your module knows how to process.

A module implementing this hook should also implement hook_token_info() in order to list its available tokens on editing screens.

Parameters

$type: The machine-readable name of the type (group) of token being replaced, such as 'node', 'user', or another type defined by a hook_token_info() implementation.

$tokens: An array of tokens to be replaced. The keys are the machine-readable token names, and the values are the raw [type:token] strings that appeared in the original text.

array $data: An associative array of data objects to be used when generating replacement values, as supplied in the $data parameter to \Drupal\Core\Utility\Token::replace().

array $options: An associative array of options for token replacement; see \Drupal\Core\Utility\Token::replace() for possible values.

\Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata: The bubbleable metadata. Prior to invoking this hook, \Drupal\Core\Utility\Token::generate() collects metadata for all of the data objects in $data. For any data sources not in $data, but that are used by the token replacement logic, such as global configuration (e.g., 'system.site') and related objects (e.g., $node->getOwner()), implementations of this hook must add the corresponding metadata. For example:

$bubbleable_metadata->addCacheableDependency(\Drupal::config('system.site'));
$bubbleable_metadata->addCacheableDependency($node->getOwner());

Additionally, implementations of this hook, must forward $bubbleable_metadata to the chained tokens that they invoke. For example:

if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
    $replacements = $token_service->generate('date', $created_tokens, [
        'date' => $node->getCreatedTime(),
    ], $options, $bubbleable_metadata);
}

Return value

array An associative array of replacement values, keyed by the raw [type:token] strings from the original text. The returned values must be either plain text strings, or an object implementing MarkupInterface if they are HTML-formatted.

See also

hook_token_info()

hook_tokens_alter()

Related topics

10 functions implement hook_tokens()

Note: this list is generated by pattern matching, so it may include some functions that are not actually implementations of this hook.

comment_tokens in core/modules/comment/comment.tokens.inc
Implements hook_tokens().
file_tokens in core/modules/file/file.module
Implements hook_tokens().
locale_test_tokens in core/modules/locale/tests/modules/locale_test/locale_test.module
Implements hook_tokens().
node_tokens in core/modules/node/node.tokens.inc
Implements hook_tokens().
statistics_tokens in core/modules/statistics/statistics.tokens.inc
Implements hook_tokens().

... See full list

1 invocation of hook_tokens()
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 74

Code

function hook_tokens($type, $tokens, array $data, array $options, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
    $token_service = \Drupal::token();
    $url_options = [
        'absolute' => TRUE,
    ];
    if (isset($options['langcode'])) {
        $url_options['language'] = \Drupal::languageManager()->getLanguage($options['langcode']);
        $langcode = $options['langcode'];
    }
    else {
        $langcode = NULL;
    }
    $replacements = [];
    if ($type == 'node' && !empty($data['node'])) {
        
        /** @var \Drupal\node\NodeInterface $node */
        $node = $data['node'];
        foreach ($tokens as $name => $original) {
            switch ($name) {
                // Simple key values on the node.
                case 'nid':
                    $replacements[$original] = $node->nid;
                    break;
                case 'title':
                    $replacements[$original] = $node->getTitle();
                    break;
                case 'edit-url':
                    $replacements[$original] = $node->toUrl('edit-form', $url_options)
                        ->toString();
                    break;
                // Default values for the chained tokens handled below.
                case 'author':
                    $account = $node->getOwner() ? $node->getOwner() : User::load(0);
                    $replacements[$original] = $account->label();
                    $bubbleable_metadata->addCacheableDependency($account);
                    break;
                case 'created':
                    $replacements[$original] = \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'medium', '', NULL, $langcode);
                    break;
            }
        }
        if ($author_tokens = $token_service->findWithPrefix($tokens, 'author')) {
            $replacements += $token_service->generate('user', $author_tokens, [
                'user' => $node->getOwner(),
            ], $options, $bubbleable_metadata);
        }
        if ($created_tokens = $token_service->findWithPrefix($tokens, 'created')) {
            $replacements += $token_service->generate('date', $created_tokens, [
                'date' => $node->getCreatedTime(),
            ], $options, $bubbleable_metadata);
        }
    }
    return $replacements;
}

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