0

This question already has an answer here:

In the admin area, to create a custom block, I go to:

Structure, Block layout, + Add custom block.

Once I create the custom block in the UI, I see a textarea field called "Body" where I can enter content.

How can I dynamically render the node author's name and profile picture in my custom block. I know I can type it in, but I would like to be able to insert some code (PHP, Twig or token) so that it pull's the author's name and profile image dynamically and prints it on the block. I do not want to use a views block, but a custom block instead.

marked as duplicate by 4k4, No Sssweat, Krishna Mohan, Yusef Mohamadi, Adrian Cid Almaguer Jul 14 '16 at 11:17

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • I'm trying to avoid using a view block and going with a custom block instead. – GTS Joe Jul 14 '16 at 6:55
3

One way to go about this is block preprocess function to retrieve the block's current node context & insert the relevant variables to be used by your Twig template. For example:

/**
 * Implements hook_preprocess_HOOK() for block.html.twig.
 */
function MYTHEME_preprocess_block(&$variables) {
  $node = \Drupal::request()->attributes->get('node');
  if (!is_null($node)) {
    $uid = $node->getOwnerId();
    $user = \Drupal\user\Entity\User::load($uid);
    if (!is_null($user)) {
      $username = $user->getDisplayName();
      $variables['$username'] = $username;
      // {{ username }} will be available within block.html.twig.
    }
  }
}
0

It's never being a good practice to add php code in block. You can use the below mention code to print a user image on nodes.

<?php
   $nid =  arg(1); 
   if($nid){
     $node = node_load($nid);
     $user = user_load($node->uid);
     print $user->name;
     print theme('user_picture', array('account' =>$user));
   }
?>

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