1

MYMODULE.module:

function MYMODULE_preprocess_node(&$variables) {

    if ($variables['node']->bundle() == 'content_type') {

        $currentUserUID = \Drupal::currentUser()->id();
        $recipients = $variables['node']->get('field_user_reference')->getValue();
        $userList = array();

        foreach ($recipients as $recipient) {

            if ($recipient['target_id'] != $currentUserUID) {
                $userList[] = \Drupal\user\Entity\User::load($recipient['target_id']);
            }

        }

        if ($variables['node']->getOwnerId() != $currentUserUID) {
            $userList[] = \Drupal\user\Entity\User::load($variables['node']->getOwnerId());
        }

        $variables['userList'] = $userList;

    }

}

FILENAME.twig.html:

{{ userList | render }}

I've also tried working with:

$recipients = $variables['node']->get('field_user_reference')->view('compact');

and tried to filter the UID in the if statement inside the foreach.


My goal is to gather all users referenced from field_user_reference, and add the owner of the node, while filtering out the currentUser() into a single array. I then need to render that array in a twig template file as a user display mode. In this instance, compact.

I am not sure if my impasse lies in twig rendering, or better preprocessing.

How do you render a preprocessed user object in a twig template file?


Notes:

$recipients = $variables['node']->get('field_user_reference')->view('compact');

does render out the referenced users in the compact view mode, however I cannot seem to filter out the current user with something like $recipient->uid[0]->target_id != $currentUserUID.

1 Answer 1

2

Before you can render a list of entities you have to build a render array:

$variables['userList'] = \Drupal::entityTypeManager()
  ->getViewBuilder('user')
  ->viewMultiple($userList, 'compact');

Now Twig is able to render the entities:

{{ userList }}    

You don't need |render, because Twig renders arrays automatically.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.