You are here

public function PlaceholderResolver::replacePlaceHolders in Typed Data API enhancements 8

Replaces the placeholders in the given text.

To ensure that the metadata associated with the token replacements gets attached to the 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'] = $resolver
  ->replacePlaceHolders('Tokens: [node:nid] [current-user:uid]', [
  'node' => $node
    ->getTypedData(),
], [], $bubbleable_metadata);
$bubbleable_metadata
  ->applyTo($build);

Parameters

string $text: The text containing the placeholders.

\Drupal\Core\TypedData\TypedDataInterface[] $data: The data to use for generating values for the placeholder, keyed by name.

\Drupal\Core\Render\BubbleableMetadata|null $bubbleable_metadata: (optional) An object to which required bubbleable metadata will be added.

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.
  • clear: A boolean flag indicating that tokens should be removed from the final text if no replacement value can be generated. Defaults to FALSE.

Return value

string The 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().

Overrides PlaceholderResolverInterface::replacePlaceHolders

File

src/PlaceholderResolver.php, line 166

Class

PlaceholderResolver
Resolver for placeholder tokens based upon typed data.

Namespace

Drupal\typed_data

Code

public function replacePlaceHolders($text, array $data = [], BubbleableMetadata $bubbleable_metadata = NULL, array $options = []) {
  $replacements = $this
    ->resolvePlaceholders($text, $data, $bubbleable_metadata, $options);
  $placeholders = array_keys($replacements);
  $values = array_values($replacements);
  return str_replace($placeholders, $values, $text);
}