manniru
2/17/2016 - 1:51 PM

Drupal 8 links, or where is my l() function

Drupal 8 links, or where is my l() function

<?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);