Drupal links

Submitted by root on Mon, 09/21/2020 - 06:52
<?php // Link use Drupal\Core\Link; $link = Link::createFromRoute('This is a link', 'entity.node.canonical', ['node' => 1]); // Url use Drupal\Core\Link; use Drupal\Core\Url; $link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' => 1])); $link = Link::fromTextAndUrl('This is a link', Url::fromUri('base:robots.txt')); // External links $link = Link::fromTextAndUrl('This is a link', Url::fromUri('http://www.google.com')); // links with only the fragment (without url) $link = Link::fromTextAndUrl('This is a link', Url::fromUri('internal:#fragment')); // Using the data provided by a user $link = Link::fromTextAndUrl('This is a link', Url::fromUserInput('/node/1'); // The param passed to fromUserInput must start with /,#,? or it will throw an exception. // Linking entities. $link = Link::fromTextAndUrl('This is a link', Url::fromUri('entity:node/1')); // Entities are a special case, and there are more ways to link them: $node = Node::load(1); $link = $node->toLink(); $link->setText('This is a link'); // And even using the route: $link = Link::fromTextAndUrl('This is a link', Url::fromRoute('entity.node.canonical', ['node' => 1])); // Drupal usually expects a render array if you are going to print the link, so the Link object has a method for that: $link->toRenderable(); ?>
Tags