cad*_*dev 8 drupal-theming drupal-8
如何404 page在Drupal 8中创建自定义?
我在后台创建了一个名为404(节点号100)的新页面(内容).我在Configuration>
Basic site设置中将其设置为404默认页面.
它适用于我在Backoffice中设置的内容.
但现在我希望它以编程方式编辑,我不知道如何创建覆盖文件.
我试图创建mytheme/templates/html--node--100.html.twig它只有当它直接请求url(node/100)时才有效,但是当你在URL上尝试随机slug并且drupal必须解决它时它不起作用.当发生这种情况时,drupal正在为我提供404 page后台内容而不是我刚刚创建的文件中的内容.
我尝试了好几种文件,如page--404-html.twig,html--node--404.html.twig,html--page--404.html.twig,...但它不工作也不
任何人都可以帮我一把吗?
ahe*_*ank 12
页面 - 系统 - 404.html.twig(或其他4xx状态的等效项)在Drupal 8.3中不再有效,因为4xx响应处理已更改.您现在需要https://www.drupal.org/node/2363987的核心补丁或类似的自定义模块挂钩,为这些页面添加模板建议:
/**
* Implements hook_theme_suggestions_page() to set 40x template suggestions
*/
function MYMODULE_theme_suggestions_page(array $variables) {
$path_args = explode('/', trim(\Drupal::service('path.current')->getPath(), '/'));
$suggestions = theme_get_suggestions($path_args, 'page');
$http_error_suggestions = [
'system.401' => 'page__401',
'system.403' => 'page__403',
'system.404' => 'page__404',
];
$route_name = \Drupal::routeMatch()->getRouteName();
if (isset($http_error_suggestions[$route_name])) {
$suggestions[] = $http_error_suggestions[$route_name];
}
return $suggestions;
}
Run Code Online (Sandbox Code Playgroud)
编辑:hook_theme_suggestions_page_alter用于修改建议数组可能更好.请参阅https://www.drupal.org/project/fourxx_templates(或https://github.com/ahebrank/fourxx_templates/blob/8.x-1.x/fourxx_templates.module)中此代码的更新版本
以下实现为页面添加了模板建议,在这种情况下,如果您在主题中创建页面--404.html.twig文件,则可以自定义页面并使用Drupal 8.5.1。
我的主题
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables, $hook) {
/**
* 404 template suggestion.
*/
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
switch ($status_code) {
case 404: {
$suggestions[] = 'page__' . (string) $status_code;
break;
}
default:
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
并创建一个名为page--404.html.twig的模板,并使用您的内容覆盖。
或,
如果要为所有错误页面添加建议,只需取出switch语句即可。
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function MYTHEME_theme_suggestions_page_alter(&$suggestions, $variables) {
/**
* error page template suggestions.
*/
if (!is_null(Drupal::requestStack()->getCurrentRequest()->attributes->get('exception'))) {
$status_code = Drupal::requestStack()->getCurrentRequest()->attributes->get('exception')->getStatusCode();
$suggestions[] = 'page__' . (string) $status_code;
}
}
Run Code Online (Sandbox Code Playgroud)