create custom page with twig & custom module
Create a custom module:
- Create a new folder in the modules/custom directory of your Drupal installation. Name it something like mypage.
- Inside the mypage folder, create a new file called mypage.info.yml and add the following code:
name: 'My Page'
type: module
core_version_requirement: ^9 || ^10
package: Custom
Create another file called mypage.routing.yml and add the following code:
mypage.page:
path: '/mypage'
defaults:
_controller: '\Drupal\mypage\Controller\MyPageController::mypage'
_title: 'My Page'
requirements:
_permission: 'access content'
mypage.module
<?php
function mypage_theme($existing, $type, $theme, $path) {
return [
'my_page_template' => [
'variables' => ['test_var' => NULL],
],
];
}
?>
Create a custom controller:
- Inside the my_module folder, create a new folder called src.
- Inside the src folder, create another folder called Controller.
- Inside the Controller folder, create a new file called MyModuleController.php and add the following code:
<?php
namespace Drupal\mypage\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Controller for the custom page.
*/
class MyPageController extends ControllerBase {
/**
* Custom page callback.
*/
public function mypage() {
$test_var = [
'title' => 'Custom Page',
'message' => 'This is a custom page created with Twig template.',
];
return [
'#theme' => 'my_page_template',
'#test_var' => $test_var,
];
}
}
templates/my-page-template.html.twig
<h1> Hello World</h1>
<p>{{ test_var.message }}</p>
留言
發佈留言