3

I'm trying to create a block that will pass a variable to its template. For now just some text but it will be an array later.

The default block variables such as label are working but I'm unable to get the value to show up in template.

Any ideas ?

FrontAppsBlock.php

namespace Drupal\custom_blocks\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
/**
 * @Block(
 *   id = "front_apps_block",
 *   admin_label = @Translation("Front Apps Block"),
 * )
 */
class FrontAppsBlock extends BlockBase implements BlockPluginInterface {

  public function build() {
    return array(
      '#theme' => 'front_apps_block',
      '#app' => 'test value',
    );
  }

}

custom_blocks.module

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'front_apps_block' => [
      'variables' => [
        'app' => null
      ]
    ]
  ];
}

block--front-apps-block.html.twig

<p>test: {{ app }}</p>
<p>label: {{ label }}</p>
6
  • Your twig variable name is test, but defined as app. Did you try outputting {{ app }} ?
    – Kevin
    Sep 18, 2017 at 15:42
  • Can you tell me what's the name of you template ? And like Kevin said, you should print {{ app }} in your twig template.
    – pbonnefoi
    Sep 18, 2017 at 16:11
  • My bad, I changed the name last second, I have {{ app }} in my template. And it is not displaying anything.
    – Mario
    Sep 19, 2017 at 7:37
  • Did you create the content() function for your block? see drupal.org/docs/8/theming/twig/…
    – Hudri
    Sep 19, 2017 at 8:38
  • I think for custom blocks the content() function is not needed since it uses the build() function.
    – Mario
    Sep 19, 2017 at 8:40

1 Answer 1

6

After long hours of searching and trying I finally found a solution. Not really sure why but it seems a naming convention has to be respected.

I changed the name of #theme and templates to start with module name, here the name is custom_blocks.

src/Plugin/Block/FrontAppsBlock.php

/**
 * @Block(
 *   id = "front_apps_block",
 *   admin_label = @Translation("Front Apps Block"),
 * )
 */
class FrontAppsBlock extends BlockBase implements BlockPluginInterface {

  public function build() {
    return [
      '#theme' => 'custom_blocks__front_apps',
      '#app' => 'test value',
    ];
  }

}

custom_blocks.module

function custom_blocks_theme($existing, $type, $theme, $path) {
  return [
    'custom_blocks__front_apps' => [
      'variables' => [
        'app' => null
      ],
    ]
  ];
}

templates/custom-blocks--front-apps.html.twig

<p>Hello: {{ app }}</p>
<p>Base Label: {{ label }}</p>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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