2

I have created a content type with some fields in Drupal 7. It output in node.tpl.php of course. But I wonder if I want to display some fields somewhere within the page.tpl.php, how to go about it. e.g. output a content types' field in the header/footer in page.tpl.php or anywhere.

7

This question is more or less a duplicate of https://stackoverflow.com/questions/8074485/drupal-7-how-to-render-custom-field. But I'd rather see the answer and question here on Drupal.stackexchange.com.

This goes into your template.php or in a module included file.

function THEME_OR_MODULE_preprocess_page(&$vars) {
  $vars['VAR_NAME'] = '';
  // Get the object and do some other checks based on what you need.
  if (($node = menu_get_object()) && $node->type) {
    // Generate a render array for the node.
    $view = node_view($node);
    // "Create" a new variable for the page.tpl.php.
    // This will expose $VAR_NAME in the page template.
    // You will most likely have to clear your cache.
    $vars['VAR_NAME'] = drupal_render($view['FIELD_NAME']);
  }
}

And then in your page.tpl.php:

HTML
<?php print $VAR_NAME; ?>
HTML

You might also have to hide the field in your node template, if you don't want to print the field twice. Check at hide() for that.

  • Thanks! It works! But I think in the page.tpl.php have to place the HTML <?php if (!empty($VAR_NAME)){print $VAR_NAME;} ?> HTML else when when you browse other pages, it will display Notice: Undefined variable: VAR_NAME in include().. – Adamtan Sep 13 '12 at 13:58
  • You can also set a default value of an empty string. See the update in my answer. – hampusn Sep 13 '12 at 14:02
  • Great! I wonder if I were to print node's orginal fields like nid, title. How to go about it then. e.g In node.tpl.php I wrote this and it works <?php print $node->nid; ?> , what about in template.tpl.php, how should I write, please advise. Thanks. – Adamtan Sep 13 '12 at 14:26
  • Which template file are you asking about? page.tpl.php? html.tpl.php? In page.tpl.php, you can access the $node as you do in node.tpl.php (print $node->nid;). In html.tpl.php, you'll have to do something like I did in my answer, but in XXX_preprocess_html(). – hampusn Sep 13 '12 at 14:32
  • Thanks! I didn't know I can access to $node in page.tpl.php just as I do in node.tpl.php for some default fields – Adamtan Sep 13 '12 at 14:54

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.