W3cubDocs

/Drupal 8

public function TwigExtension::getLink

public TwigExtension::getLink($text, $url, $attributes = [])

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 263

Class

TwigExtension
A class providing Drupal Twig extensions.

Namespace

Drupal\Core\Template

Code

public function getLink($text, $url, $attributes = []) {
  if (!$url instanceof Url) {
    $url = Url::fromUri($url);
  }
  if ($attributes) {
    if ($attributes instanceof Attribute) {
      $attributes = $attributes->toArray();
    }
    if ($existing_attributes = $url->getOption('attributes')) {
      $attributes = array_merge($existing_attributes, $attributes);
    }
    $url->setOption('attributes', $attributes);
  }
  $build = [
    '#type' => 'link',
    '#title' => $text,
    '#url' => $url,
  ];
  return $build;
}

© 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!Template!TwigExtension.php/function/TwigExtension::getLink/8.1.x