You are here

public function TwigExtension::getLink in Drupal 10

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::getLink()
  2. 9 core/lib/Drupal/Core/Template/TwigExtension.php \Drupal\Core\Template\TwigExtension::getLink()

Gets a rendered link from a url object.

Parameters

string $text: The link text for the anchor tag as a translated string.

\Drupal\Core\Url|string $url: The URL object or string used for the link.

array|\Drupal\Core\Template\Attribute $attributes: An optional array or Attribute object of link attributes.

Return value

array A render array representing a link to the given URL.

File

core/lib/Drupal/Core/Template/TwigExtension.php, line 241

Class

TwigExtension
A class providing Drupal Twig extensions.

Namespace

Drupal\Core\Template

Code

public function getLink($text, $url, $attributes = []) {
  assert(is_string($url) || $url instanceof Url, '$url must be a string or object of type \\Drupal\\Core\\Url');
  assert(is_array($attributes) || $attributes instanceof Attribute, '$attributes, if set, must be an array or object of type \\Drupal\\Core\\Template\\Attribute');
  if (!$url instanceof Url) {
    $url = Url::fromUri($url);
  }

  // The twig extension should not modify the original URL object, this
  // ensures consistent rendering.
  // @see https://www.drupal.org/node/2842399
  $url = clone $url;
  if ($attributes) {
    if ($attributes instanceof Attribute) {
      $attributes = $attributes
        ->toArray();
    }
    $url
      ->mergeOptions([
      'attributes' => $attributes,
    ]);
  }

  // The text has been processed by twig already, convert it to a safe object
  // for the render system.
  if ($text instanceof TwigMarkup) {
    $text = Markup::create($text);
  }
  $build = [
    '#type' => 'link',
    '#title' => $text,
    '#url' => $url,
  ];
  return $build;
}