以下是在Drupal 8中创建链接的一些示例。请注意,在扩展BlockBase的块中可以使用$ this-> t('some text')。如果将它们复制到另一个没有的类或在.module文件中使用它们,则可能需要将其更改为t()1。
基本链接到节点:
$node = Node::load($nid);
$build['node_link'] = $node->toLink()->toRenderable();
这将创建一个渲染数组,如下所示:
$link = [
'#type' => 'link',
'#url' => $url_object,
'#title' => 'Title of Node',
];
您可以创建渲染数组而不用这种方式加载节点:
$url_object = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
$link = [
'#type' => 'link',
'#url' => $url_object,
'#title' => $this->t('Read More'),
];
或使用核心Link类:
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
$link = Link::fromTextAndUrl($this->t('Read more'), $url);
$build['read_more'] = $link->toRenderable();
如果要在链接的文本中使用标记,则不能仅输入字符串。您需要使用render数组元素:
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid]);
$link_text = [
'#type' => 'html_tag',
'#tag' => 'span',
'#value' => $this->t('Load More'),
];
$link = Link::fromTextAndUrl($link_text, $url);
要创建绝对链接,请将此选项添加到URL,而不是链接:
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid], ['absolute' => TRUE]);
$link = Link::fromTextAndUrl($this->t('Read more'), $url);
$build['read_more'] = $link->toRenderable();
要将类添加到链接中,还需要将其添加到URL中,而不是链接中:
$options = [
'attributes' => [
'class' => [
'read-more-link',
],
],
];
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
$link = Link::fromTextAndUrl($this->t('Read more'), $url);
$build['read_more'] = $link->toRenderable();
要将查询字符串添加到您的链接,您还需要将此链接添加到URL,而不是链接:
$options = [
'query' => [
'car' => 'BMW',
'model' => 'mini-cooper',
],
'attributes' => [
'class' => [
'read-more-link',
],
],
];
$url = Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
$link = Link::fromTextAndUrl($this->t('Read more'), $url);
$build['read_more'] = $link->toRenderable();
要将链接设置为在新窗口中使用target = _blank打开:
$options = [
'attributes' => [
'target' => '_blank'
],
];
$url = Url::fromRoute('entity.media.edit_form', ['media' => $entity->id()], $options);
$link = Link::fromTextAndUrl(t('Edit'), $url);
$form['entity']['edit_link'] = $link->toRenderable();
这是分类术语页面的链接:
$url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid]);
$link = Link::fromTextAndUrl($this->t('Read more'), $url);
$build['read_more'] = $link->toRenderable();
这是节点编辑页面的链接:
$url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
$link = Link::fromTextAndUrl($this->t('Edit'), $url);
$build['read_more'] = $link->toRenderable();
要创建外部链接:
$url = Url::fromUri('http://www.example.com/');
$link = Link::fromTextAndUrl($this->t('Vist this example site'), $url);
$build['external_link'] = $link->toRenderable();
链接到首页:
$url = Url::fromRoute('<front>');
$link = Link::fromTextAndUrl($this->t('Home'), $url);
$build['homepage_link'] = $link->toRenderable();
请注意,在任何这些url对象上,您可以通过调用以下命令将url作为字符串获取:
$url->toString();
例如:
$url_string = Url::fromRoute('<front>')->toString();