Hello,

In my site project, I wish to have an image in page background which displays according to every contents (a node = a background-image).
This image will be stretchable by a script according the size of the browser. I have to insert it into the code, just before the tag <body>.
I created a image field in the type of contents (Drupal 7) to insert according to the node one specific image there.

But how may I make so that this field displays only in this place and not in the "$page[‘content’]" of "page.tpl.php" for example ?
What do I have to according to you integrate as variable ? It takes place well in the "page.tpl.php" or html.tpl.php" ? With views ? Or...

Am I clear ? I'm sorry, I'm french :/

Thanks a lot.

Comments

Anonymous’s picture

If you want it directly after the opening <body> tag then you want to put it in html.tpl.php. You can use hook_preprocess_html in your theme's template.php file to set up the extra variable.

In template.php

function mytheme_preprocess_html(&$vars) {
  $node = menu_get_object();
  if ($node && $node->nid > 0) {
    if (isset($node->field_background_image['und'][0])) { // Or whatever your field is called
      $vars['image'] = theme('image', array('path' => $node->field_background_image['und'][0]['filepath'], 'alt' => 'Alt text', 'attributes' => array('id' => 'my-id')));
    }
  }
}

Then in html.tpl.php:

<body>
  <?php echo $my_image; ?>
  <!-- Rest of the code -->
</body>

Hope that helps

Gilles G.’s picture

Thanks a lot for your response. I'll try this evening. I'm in my office ;)
But just a question : where is defined "$my_image" ?
Thx !

Anonymous’s picture

When you add it to the $vars array in the preprocess function Drupal transfers it through to your template file as a variable, I imagine using extract() or some such.

Gilles G.’s picture

I try your proposition, but doesn't work... $my_image was not defined...
But I try this and it works fine ;)

<!-- background --><?php if (!empty($node->field_background['und'][0]['filename'])): ?><?php echo theme('image', array('path' => file_build_uri('img/bg/' . $node->field_background['und'][0]['filename']), 'alt' => 'Background Image')); ?><?php endif; ?><!-- /#background -->

There isn't preprocess function in template.php... I try to do this.
Thanks iSOS !

SuperRookie’s picture

That worked for me too.