Skip to content

Instantly share code, notes, and snippets.

@samhernandez
Created August 2, 2013 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samhernandez/6143655 to your computer and use it in GitHub Desktop.
Save samhernandez/6143655 to your computer and use it in GitHub Desktop.
Sometimes you want to render a node or user field in a template. Argue about modifying stuff in hook_preprocess() all you want. Don't see the difference between using this and render() in a template.
/**
* Returns the simple, cleaned, translated value for a node or user field
* without extra Drupal markup.
*
* Examples:
* <?php print render_entity_field('user', $user, 'field_first_name'); ?>
* <?php print render_entity_field('node', $node, 'field_my_custom_field'); ?>
*
* @see http://www.computerminds.co.uk/articles/rendering-drupal-7-fields-right-way
* @param string $type 'node', 'user'
* @param object $entity
* @param string $field_name
* @param int $delta Default 0; The index of the field array value to retrieve
* @param array $options An array of options suitable for field_view_value();
* @return string
*/
function render_entity_field($type, $entity, $field_name, $delta = 0, $options = array())
{
$output = '';
$field = field_get_items($type, $entity, $field_name);
if ($field)
{
$value = field_view_value($type, $entity, $field_name, $field[$delta], $options);
if (is_array($value) && isset($value['#markup'])) {
$output = $value['#markup'];
}
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment