如何从自定义块Drupal 8返回html标记
我创建了一个新的块,就像自定义模块中的插件一样。此块必须呈现登录/注册链接。以下是函数build()代码: 如何使用如何从自定义块Drupal 8返回html标记,drupal,drupal-8,Drupal,Drupal 8,我创建了一个新的块,就像自定义模块中的插件一样。此块必须呈现登录/注册链接。以下是函数build()代码: 如何使用 还把这些李包起来 您可以使用hook\u主题来实现这一点 function hook_theme() { return array( 'block_name' => array( 'variables' => array(), 'template' => 'block_name', ),
还把这些李包起来
您可以使用hook\u主题来实现这一点
function hook_theme() {
return array(
'block_name' => array(
'variables' => array(),
'template' => 'block_name',
),
);
}
在block_name.twig文件中,可以得到如下结果
<ul class="header__top__ul">
<li class="header__top__li"><a href="{{ links.login.url}}">{{ links.login.title }}</a></li>
<li class="header__top__li"><a href="{{ links.register.url}}">{{ links.register.title }}</a></li></li>
</ul>
希望!这很有帮助。只是在链接中添加了所需的属性:
public function build() {
// Init metadata.
$cacheableMetadata = new CacheableMetadata();
$build = [
'#cache' => [
'contexts' => [
'user',
],
],
];
if ($this->currentUser->isAnonymous()) {
$build['links']['login'] = [
'#title' => $this->t('Login'),
'#type' => 'link',
'#url' => Url::fromRoute('user.login'),
'#attributes' => [
'class' => [
'header__top__a'
]
]
];
$build['links']['register'] = [
'#title' => $this->t('Register'),
'#type' => 'link',
'#url' => Url::fromRoute('user.register'),
'#attributes' => [
'class' => [
'header__top__a'
]
]
];
} else {
$build['links']['cabinet'] = [
'#title' => $this->t('My cabinet'),
'#type' => 'link',
'#url' => Url::fromRoute('user.page'),
'#attributes' => [
'class' => [
'header__top__a'
]
]
];
$build['links']['logout'] = [
'#title' => $this->t('Logout'),
'#type' => 'link',
'#url' => Url::fromRoute('user.logout'),
'#attributes' => [
'class' => [
'header__top__a'
]
]
];
}
// Apply metadata.
$cacheableMetadata->applyTo($build);
return $build;
}
并在block.twig.file中创建了一个html结构:
<div class="header__top__right">
<ul class="header__top__ul">
{% for link in content.links %}
{{ link }}
{% endfor %}
</ul>
</div>
{%用于content.links%中的链接}
{{link}
{%endfor%}
谢谢您的回答!我选择了另一种,我认为是最简单的方法,我只是在twig中添加了链接和样式块所需的属性
<div class="header__top__right">
<ul class="header__top__ul">
{% for link in content.links %}
{{ link }}
{% endfor %}
</ul>
</div>