Created
July 11, 2017 06:41
-
-
Save rindevich/5c6e9c359b4fbc438ba288f4761b7f6e to your computer and use it in GitHub Desktop.
Link examples for Drupal 8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Autoload Url and Link classes. | |
use Drupal\Core\Url; | |
use Drupal\Core\Link; | |
/** | |
* External link | |
*/ | |
$url = Url::fromUri('https://colorfield.be'); | |
$link = Link::fromTextAndUrl(t('Colorfield'), $url); | |
$link = $link->toRenderable(); | |
$link['#attributes'] = array('class' => array('external')); | |
$output = render($link); | |
/** | |
* Internal route | |
*/ | |
$url = Url::fromRoute('contact.site_page'); // a route provided in .routing.yml | |
$link = Link::fromTextAndUrl(t("Contact"), $url); | |
$link = $link->toRenderable(); | |
$link['#attributes'] = array('class' => array('internal')); | |
$output = render($link); | |
/** | |
* Entities, e.g. node | |
* @see http://stackoverflow.com/questions/35397009/creating-a-link-from-node-id-in-drupal-8 | |
*/ | |
$options = ['absolute' => TRUE]; | |
$url = Url::fromRoute('entity.node.canonical', ['node' => 1], $options); | |
//$url = $url->toString(); | |
$link = Link::fromTextAndUrl("Node title", $url); | |
$link = $link->toRenderable(); | |
$link['#attributes'] = array('class' => array('internal')); | |
$output = render($link); | |
/** | |
* Internal path | |
*/ | |
$path = '/my/path'; // prefixed with / | |
$url = Url::fromUri('internal:'.$path); | |
$link = Link::fromTextAndUrl($label, $url); | |
$link = $link->toRenderable(); | |
$link['#attributes'] = array('class' => array('internal')); | |
$output = render($link); | |
/** | |
* Anchor (current page) | |
*/ | |
$url = Url::fromRoute('<current>', array(), array('fragment' => $name)); | |
$link = Link::fromTextAndUrl($label, $url); | |
$link = $link->toRenderable(); | |
$output = render($link); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment