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.

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

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.
|improve this answer|||||

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.

   $nid =  arg(1); 
     $node = node_load($nid);
     $user = user_load($node->uid);
     print $user->name;
     print theme('user_picture', array('account' =>$user));
|improve this answer|||||

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