Skip to content

Instantly share code, notes, and snippets.

@delineas
Forked from leymannx/D8.md
Created September 10, 2017 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save delineas/ed800c9a2835eb8c5e1469e75e63ea5c to your computer and use it in GitHub Desktop.
Save delineas/ed800c9a2835eb8c5e1469e75e63ea5c to your computer and use it in GitHub Desktop.

#Drupal 8 snippets

##Create absolute URL:

$options = ['absolute' => TRUE];
$url_object = Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
// will output http://example.com/path-to-my-node

##Create absolute link object (and inner span):

$options = ['absolute' => TRUE, 'attributes' => ['class' => 'this-class']];
$node_title = Drupal\Core\Render\Markup::create('<span>' . $node_title . '</span>');
$link_object = Drupal\Core\Link::createFromRoute($node_title, 'entity.node.canonical', ['node' => $nid], $options);
// will output <a href="http://example.com/path-to-my-node" class="this-class"><span>My Node's Title</span></a>

##Simple button link

$back_text = new TranslatableMarkup('back');
$back_url  = Url::fromUri('internal:/wissen/mediathek');
$back_url->setOption('attributes', array('class' => array('back-link')));
// $variables['title_prefix'] = Link::fromTextAndUrl($back_text, $back_url);

##Drupal 8 arg() is deprecated, here is a simple alternative

function _arg() {
  $current_path = \Drupal::service('path.current')->getPath();
  return $path_args = explode('/', $current_path);
}
// $arg = _arg();

##Drupal 8 render block

function _get_block($block_id) {
  $con = \Drupal\block\BlockViewBuilder::lazyBuilder($block_id, 'full');
  $d = \Drupal::service('renderer')->renderPlain($con);
  return $d;
}
// 'content' => _get_block('languageswitcher'),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment