Nov 19, 2019 in Drupal 8, Snippets

Drupal ships with an ugly 404 page by default. in this tutorial I learn you how to add markup to it.

Add the following to your templates .theme file:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  switch ($route_name) {
    case 'system.401':
      // Unauthorized Access.
      $error = 401;
      break;

    case 'system.403':
      // Access Denied.
      $error = 403;
      break;

    case 'system.404':
      // Page Not Found.
      $error = 404;
      break;
  }
  if (isset($error)) {
    $suggestions[] = 'page__' . $error;
  }
}

After this, You can add  a twig file called page--404.html.twig (or 405,403, ...):

<div class="bg-404">
  <div class="container-fluid mt-5">
    <div class="row mt-5">
      <div class="col-md-12">
        <div class="error-template mt-5">
          <a href="/">
            <img style="max-width:200px" class="logo-image" src="/themes/logo.svg" alt="Logo">
          </a><br><br>
          <h2 class="mt-5">{{ 'This page could not be found'|t }}</h2>
          <div class="error-details">
            {{ 'The requested page is moved or could not be not found.'|t }}<br>
          </div>
          <div class="error-actions"><br>
            <a href="/" class="btn btn-primary btn-lg">
              {{ 'Go to the homepage'|t }} </a>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>