在Drupal 8中提交评论时打印用户角色



在我的Drupal站点中,用户配置文件有用户名、角色和组分类术语。有一个文章内容类型设置来接收用户的评论。每次当用户评论时,我想显示为:

Submitted by: username, role, group

我尝试通过template_preprocess函数读取角色和类别字段,如下所示:

function bartik_preprocess_comment(array &$variables) {
if (isset($variables['elements']['#view_mode'])) {
$variables['view_mode'] = $variables['elements']['#view_mode'];
}
else {
$variables['view_mode'] = 'default';
}
dd($variables);
}

但是转储没有显示"group"字段。不知道少了什么。现在,只有用户名显示。我的comments.html.twig如下:

<div class="author-comments">
<p class="comment-submitted">{{ submitted }}</p>
<div{{ content_attributes.addClass('content') }}>
{% if title %}
{{ title_prefix }}
<h3{{ title_attributes }}>{{ title }}</h3>
{{ title_suffix }}
{% endif %}
{{ content }}
</div>
</div>

任何帮助如何拉出的角色和类别字段,并插入到小树枝模板?谢谢!

好吧,我能算出来。下面是我的答案:

mytheme。主题文件:

/**
* Implements hook_preprocess_HOOK() for comment.html.twig.
*/
function mytheme_preprocess_comment(array &$variables) {
$user = Drupal::currentUser();
$user_entity = Drupal::entityTypeManager()
->getStorage('user')
->load($user->id());
$roles = $user->getRoles();
$variables['user_roles'] = $roles ;
}

这个变量可以根据需要打印在comment.html.twig上:{{ user_roles }}

最新更新