W3cubDocs

/Drupal 8

public function Token::generate

public Token::generate($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.

\Drupal\Core\Render\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()

File

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

Class

Token
Drupal placeholder/token replacement system.

Namespace

Drupal\Core\Utility

Code

public function generate($type, array $tokens, array $data, array $options, BubbleableMetadata $bubbleable_metadata) {
  foreach ($data as $object) {
    if ($object instanceof CacheableDependencyInterface || $object instanceof AttachmentsInterface) {
      $bubbleable_metadata->addCacheableDependency($object);
    }
  }

  $replacements = $this->moduleHandler->invokeAll('tokens', [$type, $tokens, $data, $options, $bubbleable_metadata]);

  // Allow other modules to alter the replacements.
  $context = array(
    'type' => $type,
    'tokens' => $tokens,
    'data' => $data,
    'options' => $options,
  );
  $this->moduleHandler->alter('tokens', $replacements, $context, $bubbleable_metadata);

  return $replacements;
}

© 2001–2016 by the original authors
Licensed under the GNU General Public License, version 2 and later.
Drupal is a registered trademark of Dries Buytaert.
https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Utility!Token.php/function/Token::generate/8.1.x