Drupal 8 hook_menu() 渲染 hook_theme()

Drupal 8 hook_menu() to render hook_theme()

我终于开始使用 Drupal 8 进行一个项目。在我的模块中,虽然我似乎无法确定如何根据路由从我的模块中呈现模板。

在 Drupal 7 中,我通常会这样做

custom.module

function union_views_menu() {
    $items = array();

    $items['home'] = array(
        'title' => 'Home',
        'description' => 'home apge',
        'page callback' => 'home_page',
        'access arguments' => array( 'access content'),
        'type' => MENU_CALLBACK
    );
    return $items;
}

function home_page() {
    return theme('home_page');
}

function union_views_theme(){
    return array(
        'home_page'     => array(
            'template'  => 'templates/home-page'
        )
  );
}

然后我会在 templates 文件夹中有一个模板

使用 Drupal 8 我到了这里:

custom.routing.yml

custom:
    path: /home
    defaults: 
        _controller: Drupal\custom\Controller\CustomController::custom
    requirements:
        _permission: 'access content'

src/Controller/CustomController.php

namespace Drupal\custom\Controller;

class CustomController {
    public function custom(){
        return array(
            '#title' => 'Custom Theme',
            '#markup' => 'This is a content.'
        );
    }
}

所有的工作都非常适合到达路线。但我似乎无法弄清楚为我的 hook_menu 创建一个 hook_theme 函数以用作回调。

想通了

添加custom.module

function custom_theme() {
    $theme['home_page'] = [
        'variables' => ['name' => NULL],
        'template' => 'home_page'
    ];

    return $theme;
}

在我的控制器中将 '#markup' 替换为:

'#theme' => 'home_page'