如何自定义在CodeIgniter 4中找不到的404页



我刚刚学习了CodeIgniter 4框架。如何自定义找不到的404页面?

转到Routes.php文件并找到

$routes->set404Override();

现在,如果你只想显示一条错误消息,那么就写

$routes->set404Override(function(){
echo "your error message";
});

而不是

$routes->set404Override();

或者如果你想返回一个视图,那么写如下:

$routes->set404Override(function(){
return view('your_filename');
});

而不是

$routes->set404Override();

//将执行App\Errors类的show404方法

$routes->set404Override('AppErrors::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 ?>

来自我的控制器:

throw new CodeIgniterExceptionsPageNotFoundException('This is my custom error message');

在@Christianto答案上展开,在4.3.7中,当使用控制器方法覆盖404时,至少我必须输入完整的命名空间路径。

// In Routes.php (full path)
$routes->set404Override('AppControllersStart::pageNotFound');
// In the controller
public function pageNotFound() {
return $this->view('error_404');
}

最新更新