How to extract and theme Drupal 7 fields out of render($page['content']?

Drupal7's page.tpl.php uses $page['content'] variable to print all the stuff. So if you want to remove <?php print render($page['content']); ?> and instead want to print content fields separately, then take note of the following.

Instead of removing print render($content) you can use the hide() function to remove the field from $content and then the render() function to print our field somewhere else in the template.

For example, for an image field called field_image_captures use hide() to prevent it from printing out in $content:

<?php
hide($content['field_image_captures']);
print render($content);
?>

The use the render() function and the field name to print the field somewhere else:

<?php
print render($content['field_image_captures']);
?>

This is called "granular theming", because you can choose to hide just one or two fields, and print the rest of them in $content without having to remove the entire $content variable just to modify a couple of fields. We didn't have such an excellent feature back in Drupal 6.

You can still use those variables like $node->body['en'][0]['safe_value'] by Contemplate module, but you will do better to use Devel and dig into the $content array. For example, with Devel module enabled place <?php dsm($node); ?> in the template to print out the node object in Krumo.

Tags:

Comments

this doesnt work i Drupal 7

Add new comment

Filtered HTML

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.