【问题标题】:Drupal 8 use suggested template when programmatically rendering nodeDrupal 8 在以编程方式渲染节点时使用建议的模板
【发布时间】:2018-05-24 09:37:34
【问题描述】:

我在 Drupal 8 模块Block 类中以编程方式渲染节点,我希望能够使用建议的模板名称之一我进入生成的 DOM 以覆盖节点的呈现方式。

不幸的是,我在模板文件夹中用于创建模板的任何建议名称都被忽略,Drupal 会呈现basic bartik node.html.twig 模板

以下是代码的相关部分:

<?php

/**
  * @Block
  */


/**
  * {@inheritdoc}
  */
public function build()
{
    $events = [];
    $eventNodes = $this->repository->findBy(['status' => 1], [ 'field_date' => 'ASC' ]);
    $viewBuilder = $this->entityManager->getViewBuilder('node');
    foreach ($eventNodes as $eventNode) {
        $event = EventMapper::fromNodeToEvent($eventNode, [
            'title' => 'field_titre',
            'start' => 'field_date',
            'end'   => 'field_fin'
        ]);

        $build = $viewBuilder->view($eventNode, 'full');
        $event['html'] = $this->renderer->renderRoot($build);

        $events[] = $event;
    }

    $months = [];
    if (count($events) > 0) {
        $indexer = new EventIndexer($events);
        $months = $indexer
            ->indexByMonths()
            ->getResults()
        ;
    }

    return [
        '#theme' => 'calendar_block',
        '#events' => $events,
        '#attached' => [
            'library' => ['calendar/calendar'],
            'drupalSettings' => [ 'events' => $events, 'monthsIndex' => $months ]
        ]
    ];
}

/**
* Custom finder in a repository service. get list of nids and load
* them.
*/

/**
  * @param array $criteria
  * @param array $orderBy
  * @param int   $limit
  * @param int   $offset
  *
  * @return array<Node>
  */
public function findBy(array $criteria = [], array $orderBy = [], $limit = null, $offset = 0)
{
    $query = $this->queryFactory->get('node');
    $query->condition('type', self::TYPE);
    foreach ($criteria as $field => $value) {
        $query->condition($field, $value);
    }

    if (!empty($orderBy)) {
        foreach ($orderBy as $field => $direction) {
            $query->sort($field, $direction);
        }
    }

    if (!is_null($limit)) {
        $query->range($offset, $limit);
    }

    $nids = $query->execute();
    $events = $this->etm->getStorage('node')->loadMultiple($nids);

    return $events;
}

/**
  * Twig fragment where the rendered event is printed.
  *
  */

{% for event in events %}
    <div class="js-calendar-slider-event calendar-slider-event" data-start="{{events[loop.index0].start|date('Y-m-d') }}" data-end="{{events[loop.index0].end|date('Y-m-d') }}">{{ event.html }}</div>
{% endfor %}

【问题讨论】:

    标签: drupal drupal-modules drupal-8 drupal-nodes


    【解决方案1】:

    你必须通过 hook_theme() 创建一个主题建议钩子

    就像我为你运行一个测试用例一样,我已经写了一个 hook_theme()

    在我的模块文件中是代码

    /**
     * Implements hook_theme().
     */
    function my_module_theme($existing, $type, $theme, $path) {
      $theme = array();
      $theme['node__contentTypeName'] = array(
        'render element' => 'content',
        'base hook' => 'node',
        'template' => 'node--contentTypeName',
        'path' => drupal_get_path('module', 'my_module') . '/templates',
      );
      return $theme;
    }
    

    然后将模板树枝文件放在 my_module/templates 文件夹中

    这是我的块代码

    namespace Drupal\my_module\Plugin\Block;
    use Drupal\Core\Block\BlockBase;
    /**
     * Provides a 'example node render block' Block
     *
     * @Block(
     *   id = "example_node_render_pulgin_block",
     *   admin_label = @Translation("example render node"),
     * )
     */
    class ExampleNodeRenderBlock extends BlockBase {
      /**
       * {@inheritdoc}
       */
      public function build() {
    
        $nid = 36;
        $entity_type = 'node';
        $view_mode = 'full';
        $view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);
        $storage = \Drupal::entityTypeManager()->getStorage($entity_type);
        $node = $storage->load($nid);
        $build = $view_builder->view($node, $view_mode);
        $output = render($build);
    
        return array(
          '#type' => 'markup',
          '#markup' => $output,
        );
      }
    }
    

    我在 twig 文件中添加了一些额外的代码,以确保我的模板正在渲染

    这是我在 template.twig 中添加的行

    <div><h1>hello its me</h1></div>
    

    最后我把我的块放在某个地方,这是结果

    希望这能解决你的问题

    谢谢

    【讨论】:

      猜你喜欢
      • 2014-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-05
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      相关资源
      最近更新 更多