duanbianweng5353 2018-09-22 06:19
浏览 163

在Drupal8自定义块中使用自定义树枝模板

I'm very new to Drupal and started learning with Drupal8 can anyone please provide me an example of Using custom twig template in Drupal8 custom block.

  • 写回答

1条回答

  • dongque3797 2018-09-22 14:04
    关注

    Follow the next steps:

    Create your custom .module file if you don't have one and add hook_theme() with defined variables names, and Twig template name.

    /**
     * Implements hook_theme().
     */
    function custom_theme() {
      return array(
       'custom_block' => array(
                'variables' => array('title' => NULL, 'description' => NULL),
                'template' => 'block--ws-custom',
            ),
      );
    }
    

    Next step is to create a block file and place the code. Go to your custom module folder, open /src/Plugin/Block/ and create file e.g. Custom.php. Include some core functions and build your custom block. Define id for your block and admin label, so you can easily find it in Structure -> Block layout and place to a region.

    Create a class and extend BlockBase. Use build() function and return an array of variables:

    namespace Drupal\custom\Plugin\Block;
    use Drupal\Core\Block\BlockBase;
    
    /**
     * Provides a 'ws custom' block.
     *
     * @Block(
     *   id = "custom_block",
     *   admin_label = @Translation("Custom Block"),
     *
     * )
     */
    class Custom extends BlockBase {
      /**
       * {@inheritdoc}
       */
      public function build() {
      // do something
        return array(
          '#title' => 'Title',
          '#description' => 'Description'
        );
      }
    }
    

    Now clear cache and go to Structure -> Block layout. Find your block and place it in the region you want.

    Next step is to create Twig file and render variables. In your themes folder open the theme that you use e.g. wstheme and open folder templates/block. Now, create a file block--custom.html.twig.

    Render variables to Twig HTML:

    {#
    /**
     * @file
     * Profile custom block.
     */
    #}
     <div class="custom--block">
        <h1>{{ title }}</h1>
        <p>{{ description }}</p>
     </div>
    

    Good luck!

    评论

报告相同问题?

悬赏问题

  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64
  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作