[英]How to Custom 404 Page Not Found in CodeIgniter 4
我剛剛學習了 CodeIgniter 4 框架。 如何自定義我的 404 頁面未找到?
Go 到您的 Routes.php 文件並找到
$routes->set404Override();
現在,如果您只想顯示一條錯誤消息,請編寫
$routes->set404Override(function(){
echo "your error message";
});
代替
$routes->set404Override();
或者如果你想返回一個視圖,那么寫如下:
$routes->set404Override(function(){
return view('your_filename');
});
代替
$routes->set404Override();
// 將執行 App\Errors class 的 show404 方法
$routes->set404Override('App\Errors::show404');
// 將顯示一個自定義視圖
$routes->set404Override(function()
{
echo view('my_errors/not_found.html');
});
要自定義 404 頁面,請根據自己的喜好修改app/Views/errors/html/error_404.php
。
對於自定義錯誤消息
在 Config\routes.php
// Custom 404 view with error message.
$routes->set404Override(function( $message = null )
{
$data = [
'title' => '404 - Page not found',
'message' => $message,
];
echo view('my404/viewfile', $data);
});
在我的視圖文件中,顯示錯誤:
<?php if (! empty($message) && $message !== '(null)') : ?>
<?= esc($message) ?>
<?php else : ?>
Sorry! Cannot seem to find the page you were looking for.
<?php endif ?>
來自我的 controller:
throw new \CodeIgniter\Exceptions\PageNotFoundException('This is my custom error message');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.