首页 > 解决方案 > 如何在 TWIG 模型中显示当前用户的图片?

问题描述

我为我的 Drupal 8 站点的主页制作了一个 TWIG 模板。

page--front.html.twig

我想在这个页面上显示当前用户的图片。

如何在 TWIG 模型中显示当前用户的图片?

标签: templatesdrupaltwigdrupal-8

解决方案


您可以使用此代码获取用户图像:

$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    if (!$user->user_picture->isEmpty()) {
      $displayImg = file_create_url($user->user_picture->entity->getFileUri());
    }else{
      $displayImg = '';    
    } 

然后将它作为变量传递给 twig,检查它是否为空,并取决于某个 img 标签内的打印。

https://www.drupal.org/forum/support/post-installation/2018-09-28/drupal-8-how-can-i-get-the-profile-picture-of-a-user

更新:

要获取图像样式 url,您可以执行以下操作:

$style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');
$url = $style->buildUrl($displayImg);

基于:https ://www.webomelette.com/how-render-your-images-image-styles-drupal-8

你应该从你的主页控制器分配树枝变量。


推荐阅读