[英]Using custom twig template in Drupal8 custom block
我是Drupal的新手,因此開始學習Drupal8,誰能給我一個在Drupal8自定義模塊中使用自定義樹枝模板的示例。
請執行以下步驟:
如果您沒有該文件,請創建自定義.module文件,並添加具有定義的變量名稱和Twig模板名稱的hook_theme()。
/**
* Implements hook_theme().
*/
function custom_theme() {
return array(
'custom_block' => array(
'variables' => array('title' => NULL, 'description' => NULL),
'template' => 'block--ws-custom',
),
);
}
下一步是創建一個阻止文件並放置代碼。 轉到您的自定義模塊文件夾,打開/ src / Plugin / Block /並創建文件,例如Custom.php。 包括一些核心功能並構建您的自定義塊。 為您的街區和管理員標簽定義ID,以便您可以輕松地在結構->街區布局中找到它並將其放置在區域中。
創建一個類並擴展BlockBase。 使用build()函數並返回變量數組:
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'
);
}
}
現在清除緩存,然后轉到“結構”->“塊布局”。 找到您的街區並將其放置在所需的區域中。
下一步是創建Twig文件並渲染變量。 在主題文件夾中,打開您使用的主題,例如wstheme並打開文件夾模板/塊。 現在,創建一個文件塊--custom.html.twig。
將變量渲染到Twig HTML:
{#
/**
* @file
* Profile custom block.
*/
#}
<div class="custom--block">
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</div>
祝好運!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.