【问题标题】:How to display the picture of the current user in a TWIG model?如何在 TWIG 模型中显示当前用户的图片?
【发布时间】:2019-04-08 22:22:14
【问题描述】:

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

page--front.html.twig

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

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

【问题讨论】:

    标签: templates drupal twig drupal-8


    【解决方案1】:

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

    $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

    更新:

    要获取图片样式的网址,您可以执行以下操作:

    $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 变量。

    【讨论】:

    • 谢谢,是自定义模块还是在 .theme 文件中?还有另一种方法吗?例如,我可以在 TWIG 年份直接获取带有 {{ user.displayname }} 的用户名和带有 {{ user.id }} 的 ID。我想用样式显示用户的图片。
    • 更新了我关于如何获取图像样式 url 的答案。抱歉,我不知道更好的解决方案,即使它听起来符合您的预期。
    • 我该怎么办?您必须将此代码放在 .theme 中还是自定义模块中?
    猜你喜欢
    • 2015-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多