如何在 Drupal 中显示一个简单的自定义页面?
How to display a simple custom page in Drupal?
最近,我尝试使用Drupal 9.2.8开发一个网站。我不习惯使用 PHP 并且很多东西对我来说看起来很奇怪(比如为什么在路径中使用 \ 而不是 / ???)。不管怎样,我想创建一个显示“Hello world”的自定义页面,所以我尝试制作一个新模块,但是当我尝试访问该页面时找不到它。
我把我所有的代码放在下面:
- modules/custom/hello/hello.info.yml
name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom
type: module
core: 8.x
core_version_requirement: ^8 || ^9
- modules/custom/hello/hello.routing.yml
hello.my_page:
path: '/hello'
defaults:
_controller: '\Drupal\hello\Controller\ExampleController::myPage'
_title: 'My first page in D9'
requirements:
_permission: 'access content'
- modules/custom/hello/src/Controller/ExampleController.php
<?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',
];
}
}
我在 index.php/admin/modules
激活了模块并在 index.php/admin/config/development/performance
清除了缓存。我尝试使用 /hello
和 index.php/hello
访问该页面,但在这两种情况下都显示“找不到页面”。
谁能告诉我我做错了什么?
编辑
我纠正了一些打字错误,但我仍然遇到同样的问题,我尝试将它安装在不同的服务器上,并且它有效,这似乎是我的服务器配置问题。
无论如何,这个模块适用于 Drupal 9.2.8,也许有人可以用它作为一个简单的例子。
谢谢。
我认为您遇到了命名空间错误。你的模块名称是“hello”,但在你的命名空间中你使用“example”而不是“hello”。如果将 ExampleController.php 和 hello.routing.yml 上的“example”更改为“hello”,模块将正常工作。
顺便说一句:您可以在没有自定义的情况下使用 Drupal PHP,但是要释放 Drupal 的全部魔力和力量,您应该学习 OOP-PHP 和 Symfony 的基础知识。
最近,我尝试使用Drupal 9.2.8开发一个网站。我不习惯使用 PHP 并且很多东西对我来说看起来很奇怪(比如为什么在路径中使用 \ 而不是 / ???)。不管怎样,我想创建一个显示“Hello world”的自定义页面,所以我尝试制作一个新模块,但是当我尝试访问该页面时找不到它。
我把我所有的代码放在下面:
- modules/custom/hello/hello.info.yml
name: Hello World Module
description: Creates a page showing "Hello World".
package: Custom
type: module
core: 8.x
core_version_requirement: ^8 || ^9
- modules/custom/hello/hello.routing.yml
hello.my_page:
path: '/hello'
defaults:
_controller: '\Drupal\hello\Controller\ExampleController::myPage'
_title: 'My first page in D9'
requirements:
_permission: 'access content'
- modules/custom/hello/src/Controller/ExampleController.php
<?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',
];
}
}
我在 index.php/admin/modules
激活了模块并在 index.php/admin/config/development/performance
清除了缓存。我尝试使用 /hello
和 index.php/hello
访问该页面,但在这两种情况下都显示“找不到页面”。
谁能告诉我我做错了什么?
编辑
我纠正了一些打字错误,但我仍然遇到同样的问题,我尝试将它安装在不同的服务器上,并且它有效,这似乎是我的服务器配置问题。
无论如何,这个模块适用于 Drupal 9.2.8,也许有人可以用它作为一个简单的例子。
谢谢。
我认为您遇到了命名空间错误。你的模块名称是“hello”,但在你的命名空间中你使用“example”而不是“hello”。如果将 ExampleController.php 和 hello.routing.yml 上的“example”更改为“hello”,模块将正常工作。
顺便说一句:您可以在没有自定义的情况下使用 Drupal PHP,但是要释放 Drupal 的全部魔力和力量,您应该学习 OOP-PHP 和 Symfony 的基础知识。