我有一个自定义模块,它创建一个具有字段元素的自定义块。
这一切都很好,但我需要为这个块设置主题。我检查了这里的其他帖子并尝试过但没有成功。
我已经启用了 twig 调试并获得了主题建议。还是没有运气。
谁能指出我正确的方向。
这是我到目前为止所拥有的:
我的模块/我的模块.模块
// nothing related in here
my_module/src/Plugin/Block/myModuleBlock.php
<?php
namespace Drupal\my_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a 'ModuleBlock' block.
*
* @Block(
* id = "module_block",
* admin_label = @Translation("My Module"),
* )
*/
class ModuleBlock extends BlockBase {
public function blockForm($form, FormStateInterface $form_state) {
$form['test'] = array(
'#type' => 'select',
'#title' => $this->t('test'),
'#description' => $this->t('test list'),
'#options' => array(
'Test' => $this->t('Test'),
),
'#default_value' => isset($this->configuration['test']) ? $this->configuration['test'] : 'Test',
'#size' => 0,
'#weight' => '10',
'#required' => TRUE,
);
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
$this->configuration['test'] = $form_state->getValue('test');
}
/**
* {@inheritdoc}
*/
public function build() {
$build = [];
$build['module_block_test']['#markup'] = '<p>' . $this->configuration['test'] . '</p>';
return $build;
}
}
my_module/templates/block--my-module.html.twig // 按照 twig debug 的建议
<h1>This is a test</h1>
<div id="test-widget">{{ content }}</div>
我还应该注意到,在我的 my_theme.theme 中我有这个,但我认为它不相关:
// Add content type suggestions.
function my_theme_theme_suggestions_page_alter(array &$suggestions, array $variables) {
if ($node = \Drupal::request()->attributes->get('node')) {
array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
}
}
至于我尝试过的是这样的:
public function build() {
return array(
'#theme' => 'block--my-module'
);
}
但还是没去。
非常感谢这里的任何帮助。
更新:所以我刚刚开始工作,但我仍然需要帮助。我移动了模板block--my-module.html.twig
到我的主题目录并且它有效。
如何让它在我的模块目录中工作?