Drupal 7: Display Page Elements Conditionally

In Drupal you often need to show page elements conditionally, usually based on variables like the URL or user identity. Fortunately, the Drupal API offers several functions that can help:

Modify the Page Header

To add a tag to the header on every page, use hook_html_head_alter() in template.php:

function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['apple_icon'] = array(
    '#type' => 'html_tag',
    '#tag' => 'link',
    '#attributes' => array('rel' => 'apple-touch-icon', 'href' => '/sites/default/files/images/apple_icon.png')

  $head_elements['favico'] = array(
    '#type' => 'html_tag',
    '#tag' => 'link',
    '#attributes' => array('rel' => 'shortcut icon', 'href' => '/sites/default/files/images/favicon.ico')

$head_elements is then called by $head in html.tpl.php, so we see the following links in our site header:

<link rel="apple-touch-icon" href="/sites/default/files/images/apple_icon.png" />
<link rel="shortcut icon" href="/sites/default/files/images/favicon.ico" />

Show Page Elements Conditionally

Place this in your template.php:

function MYTHEME_preprocess_page(&$variables) {
   $path = current_path();
   $pathalias = drupal_get_path_alias($path);
   $status = drupal_get_http_header('status');
   $patterns = 'about-contact' . PHP_EOL . 'resume';

   if ((!(drupal_match_path($path, 'admin/*'))) &&
      (!(drupal_match_path($pathalias, $patterns))) &&
      (!($status == '404 Not Found'))) {
         $variables['testing'] = '<p>test</p>';

Now that you’ve defined the $testing variable, you can call it in page.tpl.php:

<?php print render($testing); ?>

‘testing’ will only be printed on pages that a) Aren’t in the /admin tree, b) Don’t return a 404 error, and c) Don’t match the paths specified in $patterns. Note that drupal_match_path() expects arguments to be separated by an end of line character, thus the PHP_EOL. You might use PHP’s implode() function here to pass along an array instead. Also worth noting is that the admin pages are automatically aliased, so they have no corresponding node ID.


Leave a Reply

Your email address will not be published. Required fields are marked *