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 Answer
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.
-
Is there an alternate method where the markup will be placed in
page.tpl.php
instead of intemplate.php
? I'm looking for something more like:<?php if(condition) : ?> <h1>THIS GETS PRINTED</h1> <?php endif; ?>
– enchanceJun 9, 2011 at 5:19 -
1You 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?– enchanceJun 9, 2011 at 19:04
-
-
2For 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
$page
and$teaser
are view mode flags, not content types.