Drupal 8 custom block (module) create twig template file

后端 未结 2 1549
我寻月下人不归
我寻月下人不归 2021-02-09 09:40

I have a custom Module that creates a custom Block which has field elements.

This all works fine but I need to theme this block. I have checked the other posts on here

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-09 10:14

    To be able to add the twig file in your module, you need to make sure the module defines the reference, not the theme.

    You can still implement hook_theme() in the module's .module file as follows:

    function mymodule_theme($existing, $type, $theme, $path) {
      return [
        'mymodule_block'     => [
          'variables' => [
            // define defaults for any variables you want in the twig file
            'attributes' => [
               'class' => ['my-module-class'],
             ], //etc
          ],
        ],
      ];
    }
    

    Then in your block's build() implementation you can add a reference to the new theme function:

    public function build() {
        // Load the configuration from the form
        $config = $this->getConfiguration();
        $test_value = isset($config['test']) ? $config['test'] : '';
    
        $build = [];
        $build['#theme'] = 'mymodule_block';
    
        // You would not do both of these things...
        $build['#test_value'] = $test_value;
        $build['module_block_test']['#markup'] = '

    ' . $test_value . '

    '; return $build; }

    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

提交回复
热议问题