【发布时间】:2016-10-05 06:18:03
【问题描述】:
我有一个自定义模块,它创建一个具有字段元素的自定义块。
这一切都很好,但我需要为这个块设置主题。我已经检查了这里的其他帖子,但没有成功。
我已启用 Twig 调试并获得主题建议。还是没有运气。
谁能指点我正确的方向。
这是我目前所拥有的:
my_module/my_module.module
// 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 移到了我的主题目录中,并且成功了。
如何让它在我的模块目录中工作?
【问题讨论】:
-
文件是
myModuleBlock.php,但类是ModuleBlock,没有my是故意的吗?看起来不标准。