class Token (View source)

Drupal placeholder/token replacement system.

API functions for replacing placeholders in text with meaningful values.

For example: When configuring automated emails, an administrator enters standard text for the email. Variables like the title of a node and the date the email was sent can be entered as placeholders like [node:title] and [date:short]. When a Drupal module prepares to send the email, it can call the Token::replace() function, passing in the text. The token system will scan the text for placeholder tokens, give other modules an opportunity to replace them with meaningful text, then return the final product to the original module.

Tokens follow the form: [$type:$name], where $type is a general class of tokens like 'node', 'user', or 'comment' and $name is the name of a given placeholder. For example, [node:title] or [node:created:since].

In addition to raw text containing placeholders, modules may pass in an array of objects to be used when performing the replacement. The objects should be keyed by the token type they correspond to. For example:

Constants

TOKEN_INFO_CACHE_TAG

The tag to cache token info with.

Properties

protected CacheBackendInterface $cache

The token cache.

protected LanguageManagerInterface $languageManager

The language manager.

protected array[]|null $tokenInfo

Token definitions.

protected ModuleHandlerInterface $moduleHandler

The module handler service.

protected CacheTagsInvalidatorInterface $cacheTagsInvalidator

The cache tags invalidator.

protected RendererInterface $renderer

The renderer.

Methods

__construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer)

Constructs a new class instance.

string
replace(string $text, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL)

Replaces all tokens in a given string with appropriate values.

array
scan(string $text)

Builds a list of all token-like patterns that appear in the text.

array
generate(string $type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)

Generates replacement values for a list of tokens.

array
findWithPrefix(array $tokens, string $prefix, string $delimiter = ':')

Returns a list of tokens that begin with a specific prefix.

array
getInfo()

Returns metadata describing supported tokens.

setInfo(array $tokens)

Sets metadata describing supported tokens.

resetInfo()

Resets metadata describing supported tokens.

Details

__construct(ModuleHandlerInterface $module_handler, CacheBackendInterface $cache, LanguageManagerInterface $language_manager, CacheTagsInvalidatorInterface $cache_tags_invalidator, RendererInterface $renderer)

Constructs a new class instance.

Parameters

ModuleHandlerInterface $module_handler

The module handler.

CacheBackendInterface $cache

The token cache.

LanguageManagerInterface $language_manager

The language manager.

CacheTagsInvalidatorInterface $cache_tags_invalidator

The cache tags invalidator.

RendererInterface $renderer

The renderer.

string replace(string $text, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL)

Replaces all tokens in a given string with appropriate values.

Parameters

string $text

An HTML string containing replaceable tokens. The caller is responsible for calling \Drupal\Component\Utility\Html::escape() in case the $text was plain text.

array $data

(optional) An array of keyed objects. For simple replacement scenarios 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.

array $options

(optional) A keyed array of settings and flags to control the token replacement process. Supported options are:

  • langcode: A language code to be used when generating locale-sensitive tokens.
  • callback: A callback function that will be used to post-process the array of token replacements after they are generated.
  • clear: A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated.
BubbleableMetadata $bubbleable_metadata

(optional) An object to which static::generate() and the hooks and functions that it invokes will add their required bubbleable metadata.

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

When the caller does not pass in a BubbleableMetadata object, this method creates a local one, and applies the collected metadata to the Renderer's currently active render context.

Return Value

string

The token result is the entered HTML text with tokens replaced. The caller is responsible for choosing the right escaping / sanitization. If the result is intended to be used as plain text, using PlainTextOutput::renderFromHtml() is recommended. If the result is just printed as part of a template relying on Twig autoescaping is possible, otherwise for example the result can be put into #markup, in which case it would be sanitized by Xss::filterAdmin().

array scan(string $text)

Builds a list of all token-like patterns that appear in the text.

Parameters

string $text

The text to be scanned for possible tokens.

Return Value

array

An associative array of discovered tokens, grouped by type.

array generate(string $type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata)

Generates replacement values for a list of tokens.

Parameters

string $type

The type of token being replaced. 'node', 'user', and 'date' are common.

array $tokens

An array of tokens to be replaced, keyed by the literal text of the token as it appeared in the source text.

array $data

An array of keyed objects. For simple replacement scenarios: 'node', 'user', and others are common keys, with an accompanying node or user object being the value. Some token types, like 'site', do not require any explicit information from $data and can be replaced even if it is empty.

array $options

A keyed array of settings and flags to control the token replacement process. Supported options are:

  • langcode: A language code to be used when generating locale-sensitive tokens.
  • callback: A callback function that will be used to post-process the array of token replacements after they are generated. Can be used when modules require special formatting of token text, for example URL encoding or truncation to a specific length.
BubbleableMetadata $bubbleable_metadata

The bubbleable metadata. This is passed to the token replacement implementations so that they can attach their metadata.

Return Value

array

An associative array of replacement values, keyed by the original 'raw' tokens that were found in the source text. For example: $results['[node:title]'] = 'My new node';

See also

hook_tokens()
hook_tokens_alter()

array findWithPrefix(array $tokens, string $prefix, string $delimiter = ':')

Returns a list of tokens that begin with a specific prefix.

Used to extract a group of 'chained' tokens (such as [node:author:name]) from the full list of tokens found in text. For example:

Parameters

array $tokens

A keyed array of tokens, and their original raw form in the source text.

string $prefix

A textual string to be matched at the beginning of the token.

string $delimiter

(optional) A string containing the character that separates the prefix from the rest of the token. Defaults to ':'.

Return Value

array

An associative array of discovered tokens, with the prefix and delimiter stripped from the key.

array getInfo()

Returns metadata describing supported tokens.

The metadata array contains token type, name, and description data as well as an optional pointer indicating that the token chains to another set of tokens.

Return Value

array

An associative array of token information, grouped by token type. The array structure is identical to that of hook_token_info().

See also

hook_token_info()

setInfo(array $tokens)

Sets metadata describing supported tokens.

Parameters

array $tokens

Token metadata that has an identical structure to the return value of hook_token_info().

See also

hook_token_info()

resetInfo()

Resets metadata describing supported tokens.