【问题标题】:Drupal 8 hook_menu() to render hook_theme()Drupal 8 hook_menu() 渲染 hook_theme()
【发布时间】:2016-11-11 21:16:37
【问题描述】:

我终于为了一个项目潜入 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 函数以用作回调。

【问题讨论】:

    标签: drupal drupal-modules drupal-8 hook-menu hook-theme


    【解决方案1】:

    想通了

    添加custom.module

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

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

    '#theme' => 'home_page'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多