gpt4 book ai didi

php - Drupal 8 自定义 block (模块)创建 Twig 模板文件

转载 作者:可可西里 更新时间:2023-11-01 12:45:24 25 4
gpt4 key购买 nike

我有一个自定义模块,它创建一个包含字段元素的自定义 block 。

一切正常,但我需要为这个 block 设置主题。我检查了这里的其他帖子,但没有成功。

我已经启用了 twig 调试并获得了主题建议。仍然没有运气。

谁能给我指出正确的方向。

这是我目前所拥有的:

我的模块/我的模块.模块

//这里没有相关内容

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 移到了我的主题目录中,它起作用了。

如何让它在我的模块目录中工作?

最佳答案

UPDATE: So I just got it to work but I still need help. I moved the template block--my-module.html.twig to my theme directory and it worked.

How do I get it to work in my module directory?

您可以在模块根目录中创建一个名为 templates/ 的目录。将您的模板放在这里。

现在让 Drupal 知道您将模板存储在模块中。在 your_module.module 添加这个函数:

function YOUR_MODULE_theme($existing, $type, $theme, $path) {
return array(
'block__my_module' => array(
'render element' => 'elements',
'template' => 'block--my-module',
'base hook' => 'block'
)
);
}

这没有经过测试。这是我的自定义 block 的工作方式。

不要忘记清除缓存。

关于php - Drupal 8 自定义 block (模块)创建 Twig 模板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37643897/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com