I have created a content type to use for e.g. http://vih.dk/fag/fodbold. I have a title, description and a picture. I want to access the picture in an exact size in my page.tpl.php, as it has to be printed out in the css for the design to be solid. How do I access the individual fields and exactly the correct picture size in page.tpl.php?

Comments

ryivhnn’s picture

echo render($content['field_name']);

You could use the image styles thing to get images resized on upload.

works at bekandloz | plays at technonaturalist

lsolesen’s picture

That did not work for me. I tried:

print render($page['content']['field_picture']);

var_dump($content); // returns null so I cannot use your suggestion

But that did not work for me on Drupal 7?

ryivhnn’s picture

I'm an idiot. I just noticed you said page.tpl.php. It needs to go in node.tpl.php or node--type.tpl.php. Sorry.

works at bekandloz | plays at technonaturalist

lsolesen’s picture

Maybe I need to rearrange my templates a bit? http://github.com/vih/vih.dk-theme

ryivhnn’s picture

Do you have a html.tpl.php kicking around in there somewhere where I can't see it?

I don't know if you've found Lin Clark's Grok Drupal 7 theming notes in your travels but I found it really useful getting my head around the structure of how to set the different templates up.

api.drupal.org is really helpful:

And of course you need the .info file.

Clear your caches every time you add a .tpl.php file or modify the .info file otherwise it might not pick up.

Sorry if this is all repeat stuff for you :) If you want working examples (not sure how good they are but it appears to work) I can show you the templates for technonaturalist. It's my personal site/experiment/testbed/attempt-to-help-test-D7-and-whatever-modules-I'm-using running D7b2.

works at bekandloz | plays at technonaturalist

rogwan’s picture

agree with you

betarobot’s picture

Have you found a nice way of rendering field in page.tpl.php?

There is a solution: http://stackoverflow.com/questions/4662416/drupal-7-how-to-print-node-ta... But say in d6 you hadn't do any preprocess in template.php.

torotil’s picture

The fields are available deeply nested in the $page variable, so I use a simple preprocess function for easier access:

function hook_preprocess_page(&$variables) {
        if (arg(0) == 'node') {
                $variables['node_content'] =& $variables['page']['content']['system_main']['nodes'][arg(1)];
        }
}

Then I can simply render fields like this in the page.tpl.php:

if (isset($node_content) && $node_content['field_introduction']) {
    print render($node_content['field_introduction']);
}

Don't forget to hide() the field in the node.tpl.php, else it will be printed twice.

JonnyJ-1’s picture

Found this through a search, it worked perfectly, thanks a million!

sondes’s picture

I put the preprocess function in template.php and the second snippet in page.tpl.php. I updated the field to match my own. There are no errors showing but the field still isn't displayed.

Ultimately, I'm trying to print a field before the node title and this seems like the way to go. Do you have any advice?

torotil’s picture

Are you sure the preprocess function is named correctly for your theme/module and is actually called?

gagarine’s picture

Just little bit more safe in case something go wrong before.

function hook_preprocess_page(&$variables) {
  $nid = arg(1);
  if (arg(0) == 'node' && is_numeric($nid)) {
    if (isset($variables['page']['content']['system_main']['nodes'][$nid])) {
      $variables['node_content'] = & $variables['page']['content']['system_main']['nodes'][$nid];
    }
  }
}

https://interface-network.com - Interface Network is an action and research technology governance agency.

technivant’s picture

If your field is 'field_something', then in template.php:

if (arg(0) == 'node' && is_numeric($nid)) {
    if (isset($variables['page']['content']['system_main']['nodes'][$nid])) {
      $variables['node_content'] =& $variables['page']['content']['system_main']['nodes'][$nid];
      if (empty($variables['node_content']['field_something'])) {
        $variables['node_content']['field_something'] = NULL;
      }
    }
  }

in page.tpl.php:

 if (isset($node_content)) {
  if ($node_content['field_something'] <> NULL) { // Print something field
    print render($node_content['field_something']);
  }
} 

in node.tpl.php:

hide($content['field_something']);

Zenko’s picture

Hide code:

hide($content['field_name']);

marcopanichi’s picture

try this:

if( isset($node) and $node->type=='YOURNODETYPE' )
{
    $x = node_view($node);
    print $x['field_YOURFIELDNAME'] );
}
nathan.bolin’s picture

The following will give you a renderable array so that you can output it in your page.tpl with the image style(picture size) and link if required:

For single image:

$node = node_load($nid);
$output = field_view_field('node', $node, 'field_banner_image', array('label' => 'hidden'));		
$vars['banner'] = $output;		

For multiple images:

$node = node_load($nid);
$image = field_get_items('node', $node, 'field_image');
$output = field_view_value('node', $node, 'field_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail',
    'image_link' => 'content',
  ),
));

Then you can:

print render($output);

To take it a step further, you can do a little something in your template.php file to keep the logic out of page.tpl

// this goes in template.php
// check if node type page and then add to $vars array
// declaring $vars['foo'] gives you a $foo variable to use in page.tpl.php

function YOURTHEMENAME_preprocess_page(&$vars, $hook) {
	if (isset($vars['node'])) :
		if($vars['node']->type == 'page'):		
			$node = node_load($vars['node']->nid);
			$output = field_view_field('node', $node, 'field_image', array('label' => 'hidden'));		
			$vars['my_image_field'] = $output;				
		endif;
	endif;
}

So finally, you can easily print your field in page.tpl.php;

if ($my_image_field):
   print render($my_image_field);
endif;

more about field_view_field
Hope that helps someone.

CoolClick’s picture

My image is showing but I am getting this error randomly (refresh the page it goes away, do it a few more times, it does it again:

Notice: Undefined variable: my_image_field in include()

any idea why?

wooody’s picture

Try this..works perfect

	  if(isset($node->field_kort_text['und'][0]['value'])) {  
   		   print $node->field_kort_text['und'][0]['value'];
 	  }
	  
amitnaik’s picture

hi,
I was facing some problem while loading single field in my module file, so I have got it right by this...

<?php

$load_full_node = node_load($nid);
$oh = node_view($load_full_node);
$show_my_field = render($oh['field_restaurant_opening_hours']);
print $show_my_field;

?>

Note: It was a opening Hours module field. But it will work for any field.

willeifler’s picture

This worked great for me, in page.tpl.php:

<?php print render(field_view_field('node', $node, 'field_EXAMPLE)); ?>

HOWEVER: I expect much better from Drupal. Why is there not a handbook for getting these functions? I need the ability to get a field URL or any other native information in it. I have been endlessly frustrated by this type of thing since upgrading to Drupal 7.

I'm not printing variables in page.tpl.php just because I can. I need to theme page templates that are called by URL structure (another function that was confusing to upgrade), and functions like these make it possible.

Dret’s picture

This last is perect but to make rendering without label?

frankdesign’s picture

print render(field_view_field('node', $node, 'field_EXAMPLE', array('label'=>'hidden')));

See here for more options

F

web506’s picture

This worked great for me, but I switched it up a bit for this

$image = field_view_field('node', $node, 'field_image', array('label'=>'hidden'));print render($image);

Gonzalo Garcia
Freelance Webmaster

Dret’s picture

Your code works well... but give me an error on /user (login) page, this one:

include() (line 65 of /var/wwwroot/x/sites/all/themes/themename/page.tpl.php).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7663 of /var/wwwroot/x/includes/common.inc).
frankdesign’s picture

Apologies - I was in the middle of figuring this out as well. I seem to have it sorted thanks to this article and this article (for figuring out printing image fields).

 // First check that the $node variable is not empty (prevents errors on pages that don't have the $node variable e.g. pages created with Views)
if (!empty($node)) :
    // call the field from the node 
    $fieldExample = field_get_items('node', $node, 'field_example'); 
    // now check if there is anything in the variable $fieldExample  
    if ($fieldExample):
        // $fieldExample will be an array, so to figure out what element from the array you can initially use print_r ($fieldExample);
        // In the case of a single line text field, you can print that array element using the code below (where [0] is the first row of the array)
        print $fieldExample[0]['value'];
    endif; 
endif; 

In my case, I was printing an image. This is slightly more complex, so I'll add it here in case anyone needs it

 // First check that the $node variable is not empty (prevents errors on pages that don't have the $node variable e.g. pages created with Views)
if (!empty($node)) :
    // call the field from the node 
    $fieldImage = field_get_items('node', $node, 'field_image'); 
    // now check if there is anything in the variable $fieldImage  
    if ($fieldImage):
        // First I figured out the information I needed from print_r ($fieldImage);
        // With that info, I now need to create the URL to the image from the array (note: the code below gets the uri of the first image in the array)
        $imageUrl = $fieldImage[0]['uri'];
        // I also want to apply an image style to the image - for this example I'll use the 'thumbnail' image style, but you can use any image style you have created
        $style = 'thumbnail';
        // Now put it all together to create the html <img> tag
        print "<img src='" . image_style_url($style, $imageUrl) . "' />";
    endif; 
endif; 

This is working for me and so far hasn't thrown up any errors. Let me know how you get on.

F

prakharcse’s picture

My query is to get the first node content on the pages generated through the pagination on the page which is created through view

rogwan’s picture

thank you so much for this answer -:)

FNGR’s picture

This works great! Somebody knows how to do this für multiple images in the same field??

AhmadHjz’s picture

Anyone knows how to edit this code in order to display all the fields of that custom content?!

glass.dimly’s picture

I don't know why this is necessary. The following works fine for me and resolves the "Strict warning: only variables can be passed by reference" from the another comment:

      if (isset($node->type) && $node->type == 'blog') {
        $image = field_view_field('node', $node, 'field_image', 'full');
        print render($image);
      } 

This renders the image according to the configured "Full content" display settings and that's the best place to set things like image styles. In my case this is located at Structure > My Content Type > Display Settings > Full Content.

knalstaaf’s picture

A simple approach to output a field value in page.tpl.php:

  if (isset($node->my_field['und'][0]['value']) && count($node->my_field['und'][0]['value']) > 0){
    $output_field = $node->my_field['und'][0]['value'];

    print $output_field;
  }

(Use <?print print_r($node); ?> or, when using the devel module, <?php dsm($node); ?> to figure out the cascading variables.

thepaladin’s picture

how can use to get url of a field_image?

mysequel’s picture

place this in page.tpl.php

<?php
		$items = field_get_items('node', $node, 'field_YOURFIELDNAME', $node->language);
						
		print $items[0]['filename'];
?>
frankdesign’s picture

This is an unsafe way to output fields - see this article for the reasons.

See my earlier post for a safe way to print fields.

F

moinakbarali’s picture

it worked.

Tharick’s picture

Works fine :)

k_a_l’s picture

I'm honestly not sure if this is "proper", but it works!

<?php
function THEME_preprocess_page(&$vars) {
  $vars['page_banner'] = '';
  // 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.
    $vars['page_banner'] = drupal_render($view['field_image_banner']);
  }
}
?>

Then add this to your page.tpl.php:

<?php if (isset($page_banner)) : print $page_banner; endif; ?>

Jabastin Arul’s picture