You are here

public function Token::replace in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Utility/Token.php \Drupal\Core\Utility\Token::replace()
  2. 9 core/lib/Drupal/Core/Utility/Token.php \Drupal\Core\Utility\Token::replace()

Replaces all tokens in given markup with appropriate values.

Parameters

string $markup: An HTML string containing replaceable tokens.

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.

\Drupal\Core\Render\BubbleableMetadata|null $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:

$bubbleable_metadata = new BubbleableMetadata();
$build['#markup'] = $token_service
  ->replace('Tokens: [node:nid] [current-user:uid]', [
  'node' => $node,
], [], $bubbleable_metadata);
$bubbleable_metadata
  ->applyTo($build);

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 sanitization, for example the result can be put into #markup, in which case it would be sanitized by Xss::filterAdmin().

The return value must be treated as unsafe even if the input was safe markup. This is necessary because an attacker could craft an input string and token value that, although each safe individually, would be unsafe when combined by token replacement.

See also

static::replacePlain()

File

core/lib/Drupal/Core/Utility/Token.php, line 188

Class

Token
Drupal placeholder/token replacement system.

Namespace

Drupal\Core\Utility

Code

public function replace($markup, array $data = [], array $options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
  return $this
    ->doReplace(TRUE, (string) $markup, $data, $options, $bubbleable_metadata);
}