Skip to content

Instantly share code, notes, and snippets.

@jqn
Forked from jacine/field.tpl.php
Created November 23, 2015 20:10
Show Gist options
  • Save jqn/29da869199588c15e456 to your computer and use it in GitHub Desktop.
Save jqn/29da869199588c15e456 to your computer and use it in GitHub Desktop.
My default hook_preprocess_field() and field.tpl.php
<?php
/**
* Implements template_preprocess_field().
*/
function THEME_preprocess_field(&$vars) {
// If the view mode is "full" use <h2> for the field labels. Otherwise,
// assume a teaser or more compact view mode is being displayed, and use <h3>.
$vars['heading'] = ($vars['element']['#view_mode'] == 'full') ? 'h2' : 'h3';
// Add a less verbose field name class: .field-NAME
$vars['classes_array'][] = drupal_html_class($vars['element']['#field_name']);
// Use .field-body instead of .body
if ($vars['element']['#field_name'] == 'body') {
$vars['classes_array'][] = 'field-body';
}
// Remove some classes from the wrapper <div>.
$classes_to_remove = array(
'field',
'field-label-' . drupal_html_class($vars['element']['#label_display']),
'field-type-' . drupal_html_class($vars['element']['#field_type']),
'field-name-' . drupal_html_class($vars['element']['#field_name']),
'body',
'clearfix',
);
$vars['classes_array'] = array_diff($vars['classes_array'], $classes_to_remove);
}
?>
<?php
/**
* Customizations:
* - When there are more than one values for a field, output the items
* in an unordered list.
* - $heading: When view mode is 'full' it's <h2>, otherwise, it's <h3>.
* - $classes: was modified to remove some classes in template.php.
*
* @see template_preprocess_field()
* @see THEME_preprocess_field()
*
*/
$count = count($items);
?>
<?php if (!empty($items)): ?>
<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
<?php if (!$label_hidden): ?>
<<?php print $heading . $title_attributes; ?>><?php print $label; ?></<?php print $heading; ?>>
<?php endif; ?>
<?php if ($count > 1): ?>
<?php // Use a list for multiple values. ?>
<ul<?php print $content_attributes; ?>>
<?php foreach ($items as $delta => $item): ?>
<li><?php print render($item); ?></li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<?php // Omit wrapper unless attributes exist for single values. ?>
<?php if (!empty($content_attributes)): ?><div<?php print $content_attributes; ?>><?php endif; ?>
<?php print render($items); ?>
<?php if (!empty($content_attributes)): ?></div><?php endif; ?>
<?php endif; ?>
</div>
<?php endif; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment