6

The variables $page and $teaser are very helpful but is there a way to check if I'm in a different kind of Content Type? For example, if I made a content type named Products, what can I type in my template file page.tpl.php which will display HTML only if the page being viewed is of type Products?

1
  • Quick note, $page and $teaser are view mode flags, not content types.
    – RobW
    Nov 28, 2012 at 3:58

1 Answer 1

12

Place this in your theme's template.php, replacing 'THEMENAME' with the name of your theme:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['some_html'] = '';
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['some_html'] = '<p>Hello world!</p>';
  }
}

And use this in your page.tpl.php:

<?php print $some_html; ?>

Alternatively, if you want to keep the HTML string in your template file, I would do this in template.php:

function THEMENAME_preprocess_page(&$variables, $hook) {
  $variables['print_extra_header'] = false;
  if (isset($variables['node']) && $variables['node']->type == 'product') {
    $variables['print_extra_header'] = true;
  }
}

And use this in page.tpl.php:

<?php if ($print_extra_header) : ?> <h1>THIS GETS PRINTED</h1> <?php endif; ?>

Make sure to clear the cache after creating the THEMENAME_preprocess_page function, otherwise Drupal will not know it's there and it will not run.

7
  • Is there an alternate method where the markup will be placed in page.tpl.php instead of in template.php? I'm looking for something more like: <?php if(condition) : ?> <h1>THIS GETS PRINTED</h1> <?php endif; ?>
    – enchance
    Jun 9, 2011 at 5:19
  • 1
    You could do <?php if (isset($node) && $node->type == 'product') : ?><h1>THIS GETS PRINTED</h1><?php endif; ?>, but that is not recommended. Drupal uses preprocess functions so you can keep the logic out of your tpl.php files. Otherwise, tpl.php files can get messy very quickly. I added an alternative method to the answer above. Jun 9, 2011 at 6:05
  • Thanks marcvangend!I'm going to try and learn Views templates next. Any good suggestions on that one?
    – enchance
    Jun 9, 2011 at 19:04
  • How about to check if it's a Views page? How do you do that?
    – enchance
    Jun 10, 2011 at 5:36
  • 2
    For theming Views output, see Views theming basics. For checking if the page is a view in THEMENAME_preprocess_page, see hook_preprocess_page(): how to tell a views page? (I like the views_get_page_view() method best). Jun 10, 2011 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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