1

I know there are tons of posts for this but I think I have a problem with understanding how a custom block with a custom template is meant to work in Drupal 8.

Problem

My aim:

To place a custom block to display social icons. The block needs some logic (generate a url for example).

My main problem:

Everything seems to work so far but I do not get the variables passed through the twig-template (url and urlencode). They always contain the default value from the module-file (null).

What I have so far:

Files under /modules/custom/wzm_social_icons:

  • wzm_social_icons.info.yml
  • wzm_social_icons.module
  • src/Plugin/Block/WzmSocialIconsBlock.php
  • templates/block--wzmsocialicons.html.twig

I installed the module and also placed a custom block with id "socialicons". The block itself is just a placeholder with no special fields.

Files

wzm_social_icons.module

function wzm_social_icons_theme($existing, $type, $theme, $path) {
  return array('block__wzm_social_icons' =>
    array(
      'variables' => array(
        'url' => null,
        'urlencoded' => null
      ),
      'template' => 'block--wzmsocialicons'
    )
  );
}

WzmSocialIconsBlock.php

class WzmSocialIconsBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $oUrl = Url::fromRoute('<current>');
    $sUrl = $oUrl->toString();
    $sUrl = \Drupal::request()->getSchemeAndHttpHost() . $sUrl;
    $sUrlEncoded = urlencode($sUrl);

    return array(
      '#url' => $sUrl,
      '#urlencoded' => $sUrlEncoded
    );
  }
}

Nothing special in the twig-template - just the output for {{ url }} and {{ urlencode }}.

I think my main problem is to understand what needs to be declared with which key in the module-file and if the custom-block-id is used somewhere. No clue so far.

Thanks for any help!

Cheers

0

You're almost there. In your WzmSocialIconsBlock.php return the following:

return array(
  '#theme' => 'block_wzm_social_icons',
  '#url' => $sUrl,
  '#urlencoded' => $sUrlEncoded,
);

You might also want to simplify your hook_theme by letting it autodetect your template by name:

return array('block_wzm_social_icons' =>
  array(
    'variables' => array(
      'url' => null,
      'urlencoded' => null
    ),
);

And name your template templates/block-wzm-social-icons.html.twig.

  • Unfortunately not. Neither 'block__wzm_social_icons' nor 'block__wzmsocialicons' nor 'block__socialicons' nor 'block--socialicons' works for '#theme' there. Also purged cache. – Ma Nu El Feb 19 '17 at 20:17
  • I updated my answer. Indeed, be sure to clear cache. – Wim Mostrey Feb 19 '17 at 20:26
  • Helped - but did not have to change the template's file name - guess because it's declared in theme-file before. Solved - thx! – Ma Nu El Feb 19 '17 at 20:31

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.