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

How to display the picture of the current user in a TWIG model?

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

page--front.html.twig

我想在此页面显示当前用户的图片。

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

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

$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

并且您应该从主页控制器分配 twig 变量。