12

I'm periodically getting an error about $node being undefined in one of my template files.I have a simple if condition that checks the node type being displayed. I assumed $node is always available, or am I wrong?

1
  • Might want to flag this as answered so others can use this question :)
    – Bart
    Commented Aug 9, 2011 at 12:40

2 Answers 2

12

$node isn't necessarily defined, from the page.tpl.php Drupal 7 API:

$node: The node object, if there is an automatically-loaded node associated with the page, and the node ID is the second argument in the page's path (e.g. node/12345 and node/12345/revisions, but not comment/reply/12345).

8

By default, only on node pages is the $node variable defined. For the front page (a feed), view pages, comment, etc, they are not.

If you want a $node variable defined on a page that it is not a node, then you will have to edit/create the MYTHEME_preprocess_page(&$variables) function in your theme template.php file.

To avoid your error, in your template file wrap the $node variable in an

if (isset($node)) {
  // do something with $node
}

Or remove it completely

3
  • $node can be a defined variable on page.tpl.php
    – Bart
    Commented Jul 8, 2011 at 12:12
  • 1
    by default, yes, if its a NODE. If it is not, then it is not defined. Get your facts straight, and don't be downvoting a valid answer.
    – iStryker
    Commented Jul 8, 2011 at 12:36
  • Statement "Only on node pages is the $node variable define." isn't valid.
    – Bart
    Commented Jul 8, 2011 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.