[英]How to display a simple custom page in Drupal?
Recently, I tried to develop a website using Drupal 9.2.8.最近,我尝试使用 Drupal 9.2.8 开发一个网站。 I am not used to use PHP and many things looks strange for me (Like why use \\ instead of / in path ???).
我不习惯使用 PHP,很多事情对我来说看起来很奇怪(比如为什么在路径中使用 \\ 而不是 / ???)。 Anyway, I want to create a custom page displaying "Hello world", so I tried to make a new module, but when I try to access the page it is not found.
无论如何,我想创建一个显示“Hello world”的自定义页面,所以我尝试创建一个新模块,但是当我尝试访问该页面时找不到它。
I put all my code below:我把我所有的代码放在下面:
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\example\Controller\ExampleController::myPage'
_title: 'My first page in D9'
requirements:
_permission: 'access content'
<?php
namespace Drupal\example\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',
];
}
}
I activated the module in index.php/admin/modules
and clear cache in index.php/admin/config/development/performance
.我激活了
index.php/admin/modules
并清除了index.php/admin/config/development/performance
缓存。 I tried to access the page using /hello
and index.php/hello
, but in both case "Page not found" is displayed.我尝试使用
/hello
和index.php/hello
访问页面,但在这两种情况下都显示“找不到页面”。
Can you anyone tells me what I did wrong ?你能告诉我我做错了什么吗?
Thank you.谢谢你。
I think you have a namespace bug.我认为你有一个命名空间错误。 Your modules name is "hello", but in your namespace you use "example" instead of "hello".
您的模块名称是“hello”,但在您的命名空间中,您使用“example”而不是“hello”。 If you change the "example" on the ExampleController.php and hello.routing.yml to "hello", the module will work properly.
如果将 ExampleController.php 和 hello.routing.yml 上的“example”更改为“hello”,模块将正常工作。
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.顺便说一句:您可以在没有自定义 PHP 的情况下使用 Drupal,但是要释放 Drupal 的全部魔力和力量,您应该学习 OOP-PHP 和 Symfony 的基础知识。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.