如何在Drupal 8的Profile模块模板中显示profile创建者用户名?
嘿,这个问题我太熟了!要在Drupal 8的Profile模块页面模板里显示创建该profile的用户(也就是所有者)的用户名,有两种实用方法,我给你一步步讲清楚:
方法一:直接在Twig模板中调用实体数据
这是最快的实现方式,因为Profile实体本身就和它的所有者用户实体关联着,你可以直接在模板里写Twig代码获取:
打开你的profile模板文件(比如profile.html.twig),找到你想要显示用户名的位置,添加这段代码:
{# 显示profile所有者的用户名 #} {% if profile.owner.entity is not null and profile.owner.entity.access('view') %} <div class="profile-owner"> 所有者:{{ profile.owner.entity.label() }} </div> {% endif %}
profile.owner.entity:用来获取当前profile对应的所有者用户实体.label():调用用户实体的标签方法,默认情况下就是用户名(如果你的站点没修改过用户实体的标签字段,直接用这个就对了)- 加上
access('view')是为了做权限校验,确保当前登录用户有权限查看这个用户的信息,避免出现权限错误
如果想直接输出用户名的原始字段值,也可以写成{{ profile.owner.entity.name.value }},不过用label()会更灵活——要是以后你修改了用户实体的标签字段,这段代码不用跟着改。
方法二:通过主题预处理函数传递变量(更规范)
要是你希望模板代码更简洁,或者需要对所有者的信息做更多自定义处理,推荐用主题的预处理函数提前把所有者变量传到模板里:
- 打开你的主题文件夹下的
.theme文件(比如my_custom_theme.theme),添加这段PHP代码:
/** * Implements hook_preprocess_profile(). */ function my_custom_theme_preprocess_profile(&$variables) { // 获取当前的profile实体 /** @var \Drupal\profile\Entity\ProfileInterface $profile */ $profile = $variables['elements']['#profile']; // 获取所有者用户实体,校验权限后传到模板变量里 $owner = $profile->getOwner(); if ($owner && $owner->access('view')) { $variables['profile_owner'] = $owner; } }
- 回到你的
profile.html.twig模板,现在就可以直接用这个提前准备好的变量了:
{% if profile_owner is defined %} <div class="profile-owner"> 所有者:{{ profile_owner.label() }} </div> {% endif %}
内容的提问来源于stack exchange,提问作者Mathieu61
相关产品推荐
相关产品推荐

