2

I am working on customization Node template file in Drupal 8, I added another field to user in admin/config/people/accounts/fields ( my field is field_bio). Now I want to render author image( with specified image style) and field_bio in node template`.

How can I achieve this?

  • Good question, I found this How do I print/display an image in Drupal 8, using an image style I've cretaed? so give the accepted answer a try or the comment below it, let me know if it works. – No Sssweat Jun 27 '16 at 3:12
  • @NoSssweat hi, ok, I am waiting for your answer. ( I couldn't wait very much, I did it with ` if(isset($vars['node']) && $vars['node']->getType()=='blog'){ $author = $vars['node']->get('uid')->entity; $vars['author'] = array( 'bio' => isset($author->field_user_bio->value)?$author->field_user_bio->value:NULL, 'img_uri' => isset($author->user_picture->entity->uri->value)?$author->user_picture->entity->uri->value:NULL, 'full_name' => isset($author->field_full_name->value)?$author->field_full_name->value:NULL, ); }` ,do u have better solu.? – Yusef Jun 27 '16 at 8:03
  • you didn't try using Twig template? – No Sssweat Jun 27 '16 at 8:21
  • @NoSssweat I pas them as variables and in twig template I using them( because I didn't find another solution ) , if you have a solution please post it. – Yusef Jun 27 '16 at 9:39
5

If you like to do this in ui with one line of code:

1) add a view mode for user and name it "nodeview":

/admin/structure/display-modes/view/add/user

2) activate the new view mode "nodeview" at the bottom of this page in "Custom Display Settings", then you get a new tab for the view mode "nodeview". Configure which fields are displayed and how they are formatted:

/admin/config/people/accounts/display

3) Use the new view mode to render the author of the node in node preprocess:

$variables['author'] = \Drupal::entityTypeManager()->getViewBuilder('user')->view($variables['node']->getOwner(), 'nodeview');

4) Put the variable in twig

{{ author }}

This method allows full customization in ui and it is fast, because the rendered author gets cached and will be reused in every node referenced.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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