Drupal - Pass Variable to Custom Block template file

Your return array doesn't contain a #theme key. So at the moment you aren't using a template file at all.

And you probably have a mix up between the outer block and theming the content inside of the block. Your template inside has the name tcdev, because that is the name you defined at the top of the array in *_theme(), and tcdev.html.twig is where your variables will end up.

Your code would look like the following one.

function tcdev_theme($existing, $type, $theme, $path) {
  return array('tcdev' =>                  // this is the name of the template
           array(
            'variables' => array(
                'title' => 'Default title',
                'description' => null
            ),
        )
    );
}

SliderBlock.php

namespace  Drupal\tcdev\Plugin\Block;
use Drupal\Core\block\BlockBase;


/**
 * Provides a 'SliderBlock' block.
 *
 * @Block(
 * id = "slider_block",
 * admin_label = @Translation("Slider Block"),
 * )
 */

class SliderBlock extends BlockBase{
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#theme' => 'tcdev',
            '#title' => 'my title ',
            '#description' => 'my custom desc'
        );
   }
}

tcdev.html.twig

  <h2>My Custom Block{{ title }}-{{ description }}</h2>

You wrote that you saw some tutorials about it. Probably this was about two different topics, and you are trying to apply them at the same time.

  • Create custom twig templates from custom module
  • Override Twig Templates

The custom template in the first link is tcdev.html.twig. What you are trying to do with the method in the second link is for block--sliderblock.html.twig.


So that I found, you want to overwrite a default block template with a custom block (module) template, and then pass your variables to it, first of all you must make sure overwrite your template correctly because seems your current block template outputed from your Theme directory (not module):

<!-- BEGIN OUTPUT from 'themes/gttc_2016/templates/block--sliderblock.html.twig' -->

To do this first you should create a directory called templates/ in your modules root and then place your template there.

Now let Drupal know you store the template in your module. in your_module.module add this function:

function YOUR_MODULE_theme($existing, $type, $theme, $path) {
  return array(
    'block__my_module' => array(
      'render element' => 'elements',
      'template' => 'block--my-module',
      'base hook' => 'block'
    )
  );
}

Finally be careful about where you place your twig file and what you name it. Create a templates directory in your module directory, and replace the _ in the theme function name with -:
mymodule-block.html.twig

Don´t forget to clear the cache.


With the help of the answer written by Nicensin in this post:
Drupal 8 custom block (module) create twig template file

Tags:

Theming

8

Blocks