微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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 &$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移动到我的主题目录并且它工作正常.

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

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'
    )
  );
}

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

别忘了清除缓存.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐