We change some output in our field.tpl-files for body fields, depending on the input format that was used on the node (which itself depends on the user being able to modify it).

Now this worked by drilling down to $element['#object']->body["und"][0]["format"] but that's hardly best practice as illustrated by helpful articles.

But – what is the correct way to get a reliable, language-agnostic variable like $ouptut['format']?

Thanks for any infos on that!

  • As an aside, however you get the data, the best place for this sort of processing is in a preprocess hook, not in a template file. In a template, you just want simple data variables as far as possible. – Alfred Armstrong Mar 3 '15 at 12:14
  • While this is probably correct from a technical standpoint, I kind of like the workflow of having everything together in a single template file instead of juggling with hooks and template files. Drupal 8 shall enforce my education. – Paracetamol Mar 3 '15 at 12:29
  • It's not really a technical thing, just makes template files more readable and accessible to less skilled devs. – Alfred Armstrong Mar 3 '15 at 13:31

I would suggest you to create separate template based on field's text format. Here is the way:

  1. Create a TEMPLATE_preprocess_field function in template.php file of your theme.

  2. Copy and paste a file named "field.tpl.php" and rename it to "field--[your-field-name]--[its-text-format].tpl.php.

The function is :

function MYTHEME_preprocess_field($variables) {
  switch ($variables['element']['#field_name']) {

case 'body':
  $element = $variables['element'];
  $entity_type = $element['#entity_type'];
  $field_name = $element['#field_name'];
  $language = $element['#language'];
  $entity = $element['#object'];
  $values = field_get_items($entity_type, $entity, $field_name, $language);
  $item = array_shift($values);
  $format = $item['format'];
  $variables['theme_hook_suggestions'][] = 'field__' . $field_name . '__' . $format;

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.