I'm attempting to get the content type in my page preprocess function...but apparently I'm missing something. What am I doing wrong here? I'm attempting to get the $node variables first - then test from there.

function mytheme_preprocess_page(&$variables) {
   $node = \Drupal::routeMatch()->getParameter('node');
   switch ($node->getType()) {
       case "client":
           $variables['attributes']['class'][] = 'clientpage';
        case "something_else":
           // ...
  • any error messages?
    – theuni
    Commented Jun 19, 2018 at 14:38
  • Not every URL/page is a node. Before doing $node->getType() you should check for the correct object if ($node instanceof NodeInterface) ...
    – Hudri
    Commented Jun 19, 2018 at 15:40

1 Answer 1


Instead of looking at the route parameter, you can also do:

$node = $variables['node'];

Here is some example code that I have that is working from preprocess_page:

    $node = $variables['node'];

    if ($node instanceof NodeInterface) {
      $type = $node->getType();

      if ($type == 'listing_page' && trim($node->getTitle()) == 'News') {
        $variables['is_news_page'] = TRUE;

Don't forget your use ... statement if you check node is NodeInterface.

So this is definitely doable - if you are getting any error messages please post them and double check your content type machine names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.