2

I want to know the variable name for the image which renders with content; being more specific when I render my content with the following code:

<?php
  print render($content);
?>

It renders my node image, title, body, and tags. I want to put a <div> around my image, but I don't know how to specifically do it in my node.tpl.php. I found out how to render my tags, but I have no luck with images.

2
  • This bit of code will wrap a div around your image: $content['field_FIELDNAME']['#prefix'] = '<div id="my-id">'; $content['field_FIELDNAME']['#suffix'] = '</div>'; print render($content['field_FIELDNAME']);. Just replace FIELDNAME` with the machine name of your field as suggested by @jvc26 – Clive Mar 23 '12 at 8:21
  • You can use <?php echo "<pre>";print_r($node);echo "</pre>";exit; ?> to see the array structure. – Mohammad Anwar Mar 24 '12 at 17:42
3

What you need is the machine name for your field. This can be found by browsing to the content type in the admin, and seeing the value in the machine name column in the table. Within your node.tpl.php you can then access it using:

 print render($content['field_machine_name']);

By way of a more comprehensive description of how to render different elements of your node within the node.tpl.php, please see the rest of this answer.

You can implement this in a corresponding node template for your theme: In your theme directory, copy the default node.tpl.php from Drupal itself (resides in root_directory/modules/node/node.tpl.php, then make a second copy, node--content_machine_name.tpl.php. The variable you're interested in is an array which contains all the contents of the node you're about to display (from the Drupal API docs):

$content: An array of node items. Use render($content) to print them all, or print a subset such as render($content['field_example']).

Using the $content array within this template then allows you to print either sections of the array (field by field for example), or to print the whole array, or to hide sections in the print of the whole array to display later.

By way of a couple of examples:

To print a specific field output:

<div class="example_field">
    <?php print render($content['field_name']); ?>
</div>

Or to delay the printing of a field until after you've printed the rest of the content. (This is used in the default node.tpl.php to print comments after the article content .

<?php
    // Don't print the comments during the main content run
    hide($content['comments']);

    // Render the main content array
    print render($content);

    // Then render the comments last
    print render($content['comments']);
?>

Which will print the field after the main content block. For more information check out the node.tpl.php docs.

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.