1

I created a custom block and I'm trying to render it in twig file. The file gets used, as I can see its output, but my variable 'my_variable' defined in the block is not rendered:

in CustomBlock.php

public function build() {
    $build = [];

    $build['custom_block'] = [
      '#my_variable' => 'abcdef',
      '#theme' => 'custom_block',
    ];

    return $build;
}

in my_module.module:

function my_module_theme() {
  return [
    'custom_block' => [
      'template' => 'custom-block',
    ],

  ];
}

in custom-block.twig.html:

<div>{{ my_variable }}</div>

-> The twig file gets used and the div is shown, but the variable is empty/is not rendered.

2

You probably just need to define the available variables:

function my_module_theme() {
  return [
    'custom_block' => [
      'template' => 'custom-block',
      'variables' => ['my_variable' => ''],
    ],

  ];
}

You'll need to rebuild caches for the change to be picked up.

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.