Creating a custom content type page twig file in Drupal 8

You are here

At times in Drupal 8, a site builder needs to create a custom content type page twig file. In Drupal 8 you can't just create it like you do with other twig files that come with Drupal core , you have to register a suggestion with the theme array. Adding The functions below to your template.theme will give the developer the ability to add a twig file called page--<content_type_name>.html.twig. Overriding the default page twig file in your theme

/**
 * Implements hook_theme_suggestions_HOOK_alter() for form templates.
 * @param array $suggestions
 * @param array $variables
 * Needing to add page--<content_type_name>.html.twig to build
 */
function theme_name_theme_suggestions_page_alter(array &$suggestions, array $variables) {
    //-- accesses the content type on page landing
    $access_content_type = _theme_name__access_content_type(); //-- custom function
    //
    if ($access_content_type != NULL ) {
        $suggestions[] = 'page__' .$access_content_type;
    }
}

Access the current content type that is being loaded on this page

/**
 * Access current content type on page load.
 * Changing the function name protects you 
 * from other modules.
 * @return mixed
 */
function _theme_name__access_content_type(){
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
       return  $node->bundle();
    }
    return NULL;
}