php – Drupal 8自定义块(模块)创建twig模板文件

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – Drupal 8自定义块(模块)创建twig模板文件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个自定义模块,可以创建一个具有字段元素的自定义块.

这一切都很好,但我需要主题这个块.我已经检查过这里的其他帖子,并试着没有运气.

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

任何人都可以指出我正确的方向.

这是我到目前为止:

my_module / my_module.module

//这里没什么关系

my_module / SRC /插件/块/ 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 &amp;$suggestions,array $VARiables) {
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions,1,'page__node__' . $node->getType());
  }
}

至于我试过的是这个:

public function build() {
    return array(
      '#theme' => 'block--my-module'
    );
}

但仍然没有去.

这里的任何帮助非常感谢.

更新:所以我只是让它工作,但我仍然需要帮助.我将模板块 – my-module.html.twig移动到我的主题目录并且它工作正常.

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

您可以在模块根目录中创建名为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'
    )
  );
}

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

别忘了清除缓存.

脚本宝典总结

以上是脚本宝典为你收集整理的php – Drupal 8自定义块(模块)创建twig模板文件全部内容,希望文章能够帮你解决php – Drupal 8自定义块(模块)创建twig模板文件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。