I want to print my fields in tpl.php files as cleanly as possible. To do this, I have used the following code in my template.php file:

function print_field($field_name, $format = 'safe_value') {

if (arg(0) == 'node' && is_numeric(arg(1))) {
  // Get the nid
  $nid = arg(1);

  // Load the node if you need to
  $node = node_load($nid);

$field= field_get_items('node', $node, $field_name);

if ($format == 'url') {
    print file_create_url($field[0]['uri']);
} else {
print $field[0]["$format"];

Now, I can print my fields in my tpl.php file in a clean manner, without any unnecessary mark-up or labels:

<?php print_field('field_section') ?> -- Prints the field with safe formating

<?php print_field('field_title', 'value') ?> -- Prints the field in Raw

<?php print_field('field_intro_image', 'url') ?> -- Prints the image url of a field

It all works fine, but I get this error message:

Notice: Undefined index: safe_value in print_field() (line 19 of template.php).

How I can resolve this?

Also, is it possible to just enter value or url in my tpl.php file without wrapping them in quote marks?


The problem is with your function, not the template.

Ideally you should check if the index exists, e.g.

print array_key_exists($format, $field[0]) ? $field[0]["$format"] : '';


print !empty($field[0]["$format"]) ? $field[0]["$format"] : '';


print @$field[0]["$format"] ? $field[0]["$format"] : '';

Alternatively you can ignore the notices in PHP config (php.ini) or in Drupal admin.

Or you can just prefix the field with @ to silence/suppress any errors (usually not recommended), e.g.

print @$field[0]["$format"];

Have you seen field_view_value() which already does what you're attempting, i.e. getting the value of a field without additional markup.


$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

(For reference taken from: https://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way which is well worth a read.)

  • I have read that link, but as I understand it (any my understanding could be wrong!!) that requires two lines of code in the tpl.php file. I would like it to be as cleanly as possible, as I want my tpl.php files to be easy to read! – big_smile Mar 20 '15 at 12:13
  • I understand, I was suggesting you place that in your function. Generally I find that there are a slew of advantages to using the Drupal API compared to using your own functions, security, portability, compatibility etc. Once you start using it you start seeing how it all fits together and why, which often isn't obvious. Like in this case you wouldn't have to worry if there isn't a safe_value, the best fit would be auto magically produced for you. – bloke_zero Mar 20 '15 at 16:28

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.