Node templates and the mysterious render function in Drupal 7

It's complicatedIf you have a Drupal 7 site and you want to change the output of a content-type you can do it via the UI or you can create a so called node template and copy it to your theme.

The name of the template has to be node--[name of content-type].tpl.php (Watch the two hyphens ... In Drupal 6 it was one :) ). If your content-type is called house the name of the template file has to be node--house.tpl.php.

In Drupal 6 days I often used the content template module to figure out how to access the value of a field. That doesn't work anymore.

In Drupal 7 the access is (on one hand) much easier. You can use the render function like this

$yourfieldname = render($content['field_yourfieldname']);

You get the fields value as configured in structure -> content-type -> manage display. Very cool!

When you use node references (like me) things seem to get more complicate:

Where is my value?

I have a content-type (house) with a reference to another content-type (material) with a reference to another content-type (manufacturer). In manufacturer I have a textfield as option list (field_industry). This option list has of course keys and values.

I want to access the value of the field field_industry from content-type manufacturer in node--house.tpl.php. The problem is that I didn't found the value of the field in the $content array, only the key :(.

After struggling around for hours I finally found a solution

  1. Edit node--house.tpl.php
  2. Determine the nid of the manufacturers node.
  3. $node = node_load($nid); // nid of manufacturer
    $industry = field_get_items('node', $node, 'field_industry');
    $output = field_view_value('node', $node, 'field_industry', $industry[0] );
    print render($output);

It works and the output is the value of the key of the field field_industry of the node ID ... of the content-type manufacturer which is referenced by material which is referenced by house #pfffft

If you have an easier solution without the necessity of an additional node_load(), please comment.



Thanks for this post!
Is there really no possibility to use "render($content..." or "drupal_render" and just get the field value?
Maybe via adding a rendermode?

How can I determine the nid of the manufacturer?