7

What is the best practice for using a field as an "attribute" in a node template with Drupal 7? I am using the term "attribute" loosely here to mean something that can't be concretely rendered as an HTML fragment; rather, it gets rendered inside an HTML fragment somewhere in a template.

The field API makes it very easy to wrap a "content" field with HTML so it can be rendered in a template, many times with out needing to edit the node template at all, due to the way render trees work.

Consider a content type such as

  • Title (title)
  • Body (body)
  • Extra (field_extra)

Where field_extra is just something that I want to tack onto the node title, eg

<?php if (!$page && $title): ?>
<h2><?php print $title ?> &mdash; <?php print $extra; ?></h2>
<?php endif; ?>
print render($content);

This is a very, very simplified example to illustrate what I am talking about.

I could just access

$extra = trim($field_extra[0]["safe_value"]);

but I would have to go through some show()/hide() logic depending on how things where configured, and directly accessing fields is discouraged.

I could make a theme_field(), such as

function mytheme_field__field_extra ($variables)
{
  $items = $variables["items"];
  return count($items) == 0 ? "" : trim(drupal_render($items[0]));
}

and then use render(), but I would still have to go through the show()/hide() shenanigans and I am not really rendering the field, just trying to get a plain version of it to use somewhere.

Or, should this really be handled by a template_preprocess_node(), eg

function mytheme_preprocess_node (&$variables)
{
  $node = $variables["node"];
  $language = $node->language;

  if (isset($variables["field_extra"])
      && isset($variables["field_extra"][$language])
      && isset($variables["field_extra"][$language][0])) {
        $variables["extra"] = trim($variables["field_extra"][$language][0]["safe_value"]);
  }
}

I know all of these will work. I am really interested in what is the best practice here. I suspect that the template_preprocess_node() is the best way to handle this, but I have not seen anything definitive about this case.

Thanks.

1 Answer 1

1

Is there a reason to not just set the format to "<hidden>" in the content type's "manage display"? Then it will never render but you still have it if you want it.

If you really want to do this programatically, the best practice, for me, is to use a module not your theme. Why? Because if your theme changes... do you want extra to show? Nope, so make it independent of the theme by putting it in a module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.