简体   繁体   中英

Using custom twig template in Drupal8 custom block

我是Drupal的新手,因此开始学习Drupal8,谁能给我一个在Drupal8自定义模块中使用自定义树枝模板的示例。

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 eg 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 eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM