Drupal 8 Page Theme Suggestions

I have decided to update one of our sites to Drupal 8, I know it isn’t ready for production but it isn’t a critical site and needed some work done anyway.

The biggest issue I hit was working out how to change the page template based on content type. While most of the site shares the same page template and just alters the node template our landing pages are structurally very different. There is now a bunch of theme_suggestions_* functions that should make life easier however the hardest part was working out how to get the content type so it could be changed.

Below shows what I ended up doing. This code belongs in THEMENAME.theme inside the template root directory, replace THEMENAME with the name of your theme and landing_page with the machine name of your content type. Also note that our theme file is called page–landing_page.html.twig, Drupal will automatically replace the double underscores with dashes, it won’t work otherwise.

        function THEMENAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
                if($node = \Drupal::routeMatch()->getParameter('node')){
                        if($node->getType() == 'landing_page'){
                                $suggestions[] = 'page__landing_page';
                        }
                }
        }