1

I am trying to pass variables to a custom block in a module. I can see that the custom block is used in the code, however I cannot get the variables to show up.

Any help much appreciated:

I am themeing the block in the module file

function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'block__etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

I am building the render array

class SocialBlock extends BlockBase implements BlockPluginInterface {
/**
 * {@inheritdoc}
 */
public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'block__etypeservices',
      '#facebook' => $facebook,
   ];
 }


}

and here is the template

{%
    set classes = [
   'block',
   'block-social-icons',
   ]
%}
<div{{ attributes.addClass(classes) }}>
   <ul class="list-style-none">
    {% if facebook %}
    <li><a href="https://www.facebook.com/{{ facebook }}" target="_blank">Facebook</a></li>
    {% endif %}
   </ul>
</div>

Can anybody see why this is not working?

  • Your code must work. Maybe your config is bad? Try to replace "'#facebook' => $facebook" by "'#facebook' => "TEST"" – Rainer Feike Sep 10 '18 at 12:13
  • And your template filename must replace the underscore by a dash! So it should be named block--etypeservices.html.twig – Rainer Feike Sep 10 '18 at 12:17
1

For a custom template use your own theme hook etypeservices:

function etypeservices_theme($existing, $type, $theme, $path) {
   return [
    'etypeservices' => [
      'variables' => [
        'facebook' => '',
     ],
   ],
];
}

Which uses it's own variables space:

public function build() {
    $config = \Drupal::config('etypeservices.settings');
    $facebook = $config->get('facebook');
    return [
      '#theme' => 'etypeservices',
      '#facebook' => $facebook,
   ];
 }
}

etypeservices.html.twig

{{ facebook }}

The content of the block is a normal render array, which can contain one or more custom templates to make them accessible in theming. These custom templates are reusable, not only in blocks.

In a module you can override the block template, as you tried to do by using block__..., but you need this in very rare cases. In drupal core there is only one. Then you will inherit the variables of the base hook block.

But normally you leave the block template as it is, so that it can be themed on it's own.

| improve this answer | |

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.