Drupal 8:在自定义模块中创建块时如何使用变量呈现模板?

时间:2016-08-10 12:56:56

标签: templates drupal module block

我正在尝试在我自己的自定义模块中的块中渲染模板。模板正确呈现但没有变量。

ranking.module

<?php

function ranking_theme($existing, $type, $theme, $path) {

    return array(
        'block__ranking' => array(
            'template' => 'block--ranking',
            'variables' => array('title' => 'test'),
        ),

    );
}

RankingBlock.php

<?php
/**
 * @file
 * Contains \Drupal\ranking\Plugin\Block\RankingBlock.
 */

namespace Drupal\ranking\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Ranking' Block
 *
 * @Block(
 *   id = "ranking_block",
 *   admin_label = @Translation("Ranking Block"),
 * )
 */
class RankingBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#title' => 'This is an awesome title'
        );
    }

}

当然,我尝试用{{title}}显示变量(在templates / block - ranking.html.twig中)

我主要关注(但不仅仅是)this tutorial

你能告诉我我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我终于解决了这个问题。缺少以下行: &#39;#主题&#39; =&GT; &#39;排名&#39;在RankingBlock.php中

<?php
/**
 * @file
 * Contains \Drupal\ranking\Plugin\Block\RankingBlock.
 */

namespace Drupal\ranking\Plugin\Block;
use Drupal\Core\Block\BlockBase;

/**
 * Provides a 'Ranking' Block
 *
 * @Block(
 *   id = "ranking_block",
 *   admin_label = @Translation("Ranking Block"),
 * )
 */
class RankingBlock extends BlockBase {
    /**
     * {@inheritdoc}
     */
    public function build() {
        return array(
            '#theme' => 'ranking',
            '#title' => 'This is an awesome title'
        );
    }

}