1
votes

I am working with Drupal 8 and Twig. I have a Content Type with a field "Team Members" that is an Entity Reference to User.

Entity Reference to User

On the Content of this Content Type I set the Team Members.

Team Members set on Content

How can I get the URLs of these users' profile pictures in my Twig template?


What I have tried:

{% for key, item in content.field_team_members if key|first != '#' %}
    <p>{{ dump(item['#options'].entity.user_picture.0|keys) }}</p>
{% endfor %}

Which results in:

array(5) {
  [0]=>
  string(9) "target_id"
  [1]=>
  string(3) "alt"
  [2]=>
  string(5) "title"
  [3]=>
  string(5) "width"
  [4]=>
  string(6) "height"
}

I can get the user_picture entity, but cannot see a way to get the profile image url from this

I also thought that by just doing:

{% for key, item in content.field_team_members if key|first != '#' %}
    {{ item['#options'].entity.user_picture.0 }}
{% endfor %}

would display the image, but I receive an error.

The website encountered an unexpected error. Please try again later.

Exception: Object of type Drupal\image\Plugin\Field\FieldType\ImageItem cannot > be printed. in Drupal\Core\Template\TwigExtension->escapeFilter() (line 441 of > core/lib/Drupal/Core/Template/TwigExtension.php).

Also, I have noticed that the "content.field_team_members" array contains different data depending on whether I am logged into Drupal or not. The for loop does not even loop if I am not logged in, which means this approach wouldn't work for visitors to my site, so there must be a different approach.

2

2 Answers

1
votes

I resolved this by adding a preprocess function to my mythemename.theme file which adds the profile picture URL to the $variables array that is exposed to Twig.

Preprocess function:

function mythemename_preprocess_ds_1col__node_portfolio_item(&$variables) {

  $teamMembers = array_filter(array_keys($variables['content']['field_team_members']), 'is_int');
  $teamMembersCount = count($teamMembers);

  for ($i = 0; $i < $teamMembersCount; $i++ ) {
    $user = &$variables['content']['field_team_members'][$i];
    $user['imgUrl'] = file_create_url($user['#options']['entity']->user_picture->entity->getFileUri());
  }

So the URL can be accessed via Twig:

{% for key, item in content.field_team_members if key|first != '#' %}
    <img src="{{ item['imgUrl'] }}" />
{% endfor %}

The second problem

"content.field_team_members" array contains different data depending on whether I am logged into Drupal or not

was resolved based on permissions. On example.com/admin/people/permissions the "View User Information" field must be checked for Anonymous User

Permission Setting

0
votes

I got something similar to work by replacing {{ entity.field.0 }} with {{ entity.field.value }} or {{ entity.field.0.value }}.

So, in your case {{ item['#options'].entity.user_picture.value }}.

I'm not sure if this is the "correct" approach but it seemed to work with my data.