首页 > 解决方案 > 如何在 Drupal 中显示一个简单的自定义页面?

问题描述

最近,我尝试使用 Drupal 9.2.8 开发一个网站。我不习惯使用 PHP,很多事情对我来说看起来很奇怪(比如为什么在路径中使用 \ 而不是 / ???)。无论如何,我想创建一个显示“Hello world”的自定义页面,所以我尝试制作一个新模块,但是当我尝试访问该页面时找不到它。

我把我所有的代码放在下面:

name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom

type: module
core: 8.x
core_version_requirement: ^8 || ^9
hello.my_page:
  path: '/hello'
  defaults:
    _controller: '\Drupal\hello\Controller\ExampleController::myPage'
    _title: 'My first page in D9'
  requirements:
    _permission: 'access content'

<?php
namespace Drupal\hello\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Provides route responses for the Example module.
 */
class ExampleController extends ControllerBase {

  /**
   * Returns a simple page.
   *
   * @return array
   *   A simple renderable array.
   */
  public function myPage() {
    return [
      '#markup' => 'Hello, world',
    ];
  }
}

我在 .in 中激活了模块index.php/admin/modules并清除了缓存index.php/admin/config/development/performance。我尝试使用/helloand访问页面index.php/hello,但在这两种情况下都显示“找不到页面”。

谁能告诉我我做错了什么?

编辑

I corrected some typing mistakes, but I still had the same problem, I tried to install it on a different server, and it works, it seems to be a problem with my server configuration.

Anyway, this module works on Drupal 9.2.8, maybe someone can use it as a simple example.

Thank you.

标签: phpmoduledrupal

解决方案


I think you have a namespace bug. Your modules name is "hello", but in your namespace you use "example" instead of "hello". If you change the "example" on the ExampleController.php and hello.routing.yml to "hello", the module will work properly.

BTW: You can use Drupal without custom PHP, but to unleash the full magic and power of Drupal you should learn the basics of OOP-PHP and Symfony.


推荐阅读