2

I have this preprocess function in my theme:

function hotness_preprocess_node(&$vars) {
  $node = empty($vars['node']) ? FALSE : $vars['node'];
  $vars['hotness_is_article_page'] = ($node && node_is_page($node) && $node->type == 'spot') ? TRUE : FALSE;
}

The other stuff I do here (not shown) works fine. However, I get an undefined error when I try to use $hotness_is_article_page in my theme tpl files (specifically region--branding.tpl.php). I am using Omega, if that matters.

For some reason I only seem to be able to create variables accessible in tpl files in my hotness_preprocess() function, but not page or node hooks. This is not ideal, as hotness_preprocess() runs several times per page load.

What am I doing wrong?

  • Safe to assume that you cleared caches and retested? – mpdonadio Dec 3 '11 at 15:33
  • Yes - min char limit is a stupid requirement. – Justin Dec 3 '11 at 18:01
5

The variables added from hook_preprocess_node() are only available in node.tpl.php, or any other node template that Drupal will pick up because any suggestion contained in $variables['theme_hook_suggestions'] (Drupal 7), or $variables['template_files'] (Drupal 6).

To add a variable used by a region template file, you need to use a different preprocess function: hook_preprocess_region(), or hook_preprocess(). The latter is a generic preprocess function; the second parameter passed to that preprocess function tells it which theme hook is going to be preprocessed.

This means that, by default, the region preprocess function doesn't have access to $variables['node']; if you want to access the node object associated with the page being viewed, if there is one, you need to use similar code used in template_preprocess_page() and add the following line to your preprocess function:

if ($node = menu_get_object()) {
  $variables['node'] = $node;
}

The function returns FALSE if the page is not associated with a node; this could happen, for example, if the user is visiting example.com/user/1.

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.