drupal-themingdrupal-8

Custom 404 template file in Drupal 8


How can I create a custom 404 page in Drupal 8?

I have created a new page(Content) in the backoffice called 404 (node number 100). I have set it as the 404 default page at Configuration > Basic site settings.

Settings

It works with the content that I have set in the Backoffice.

But now I want it to be editable programatically and I don't know how can I create the overriding file.

I have tried to create mytheme/templates/html--node--100.html.twig and it works only when the request its directly that url (node/100), but it doesn't work when you try a random slug on the URL and drupal has to resolve it. When this happens, drupal is serving me the content that the 404 page has in the backoffice and not in the file that I have just created.

I have tried several files like page--404-html.twig, html--node--404.html.twig, html--page--404.html.twig,... but it doesn't work neither

Can anyone lend me a hand?


Solution

  • page--system--404.html.twig (or the equivalent for other 4xx statuses) no longer works in Drupal 8.3 as the 4xx response handling has changed. You'll now need the core patch from https://www.drupal.org/node/2363987 or a similar custom module hook that adds template suggestions for these pages:

    /**
     * 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;
    }
    

    EDIT: It's probably nicer to use hook_theme_suggestions_page_alter to modify the suggestions array. See an updated version of this code in https://www.drupal.org/project/fourxx_templates (or https://github.com/ahebrank/fourxx_templates/blob/8.x-1.x/fourxx_templates.module)