Question

I have a Drupal 7 site with a content type of event.

I have a taxonomy called "event types" that has 5 options (Party, Conference, Meeting, etc)

I have one template named node--event.tpl.php for styling the standalone event nodes.

How can I detect which taxonomy terms apply to a given event node from within the template file? I need to change some of the presentation logic based on the taxonomy term associated with the event.

I am not using the taxonomy in the URL, so I need to find another method for detecting the event type. Devel doesn't seem to show me any values of taxonomy terms to work with.

Was it helpful?

Solution

As alluded to in the first answer, you should use a preprocess function, but probably for the node template.

For the node.tpl.php template (and all derivatives) the function is defined as

MYTHEME_preprocess_node(&$vars) {
}

and should appear your theme's template.php file.

You must clear the Drupal cache in order to reset the theme registry such that Drupal recognizes and executes this function.

The $vars argument of the function is an array that contains all the template variables which subsequently appear in the tpl file ($vars['foo'] will be leveraged as <?php print $foo; ?> in the tpl file).

This also includes the native $node object, which will allow you to inspect $node->taxonomy, and create any subsequent variables accordingly. You can leverage these in the tpl file.

The best way to inspect and discover the components of $vars is to use the Devel module's dpm() function, which nicely prints any variable to the theme's messages box.

So, enable devel, create the following in template.php, clear cache, refresh viewing a node, and work from there.

MYTHEME_preprocess_node(&$vars) {
  dpm($vars);
}

You may also be interested in my session on Drupal preprocess functions from Drupalcon Copenhagen or the Drupal handbook page.

Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top