Giving Nodes a Wardrobe - meet page_is_node() and drupal_is_front_page()

If you've been using Drupal for awhile, you probably understand template hinting and how you can format one content type differently than another, by having a template file such as

node--my-content-type.tpl.php

Recently, however, I had the need to format a single content type differently depending on where it was presented:

  • front page
  • node page 
  • taxonomy term page

The difference in presentation wasn't just a matter of CSS properties, the structure of the content and the fields presented would be different. The logic was as follows:

  • If the page being viewed is the front page, use format A
  • If the page being viewed is a taxonomy page, use format B
  • Otherwise, use format C

The solution is to make use of Drupal's functions. 

drupal_is_front_page()

returns true if the current page is the site's front (home) page, and

node_is_page($node)

returns true if the current node is being displayed on its node page (if it's a teaser, elsewhere, then this will be false).

So, to meet the requirement, the logic would be:

if (drupal_is_front_page()) {

   do front page formatting

}

elseif (node_is_page($node)) {

  do node page formatting 

}

else {

  do other formatting

}

 

If necessary, we could check the pattern of the request URL in the last test rather than simply defaulting. This code can be in the node template (where if:/endif; would typically be used instead of if{}/else{}), or the testing and some or all of the output could be preprocessed in template.php.


Type:
Tip
Tags:
D7
php
Drupal