Make a Drupal Field available in the Page Template

Sometimes there’s a need to render a Drupal field’s value outside the scope of a node template. I used to achieve this with either Display Suite or CCK Blocks. As I’m about to change my workflow towards putting more theming stuff back to code (where it belongs) instead of clicking around slow and clumsy web interfaces I needed another solution.

1. Implement template_preprocess_page() in your theme’s template.php

Of course you’ll need to replace MYTHEME with the name of your theme, $stage_images with an arbitrary name of your choice and field_stage_images with the name of the field you want to render.

 *  Preprocess page.tpl.php to add some variables that help theming
function MYTHEME_preprocess_page(&$vars){
  // Make the field "field_stage_images" of content type "page" 
  // available as variable to use in page.tpl.php
  $vars['stage_images'] = '';
  // 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['stage_images'] = drupal_render($view['field_stage_images']);

2. Print the newly created variable

Your new variable is now available inside your theme’s page.tpl.php. Just print it where ever you want:

<?php if($stage_images) : ?>
  <div id="stage">
    <div class="row">
      <?php print $stage_images; ?>
<?php endif; ?>

I found this on Stackexchange with a reference to the original topic over at Stackoverflow. Thanks for posting!

Leave a Reply