Styling rows in views

If you're using Drupal without Views... you're probably doing it wrong (sic). Views really are almost a the only way to have full control over any content listing, with minimal effort.  You can even customize things on a per-field basis via template overrides. But how do you add particular classes to individual rows?

In case you haven't run in to this particual problem, here goes: you have a view that you like. You then decide that rows that are sticky, should get a differently colored background. How hard can that be?

Appaerntly, quite! I (still) cannot find a way to access the individual row data inside the template file, in order to have per row classes the easy way (TM), so the only road left was via a preprocess function, located in template.php . You should obviously rename the function, substituting mytheme with you actual theme name. Here goes:

function mytheme_preprocess_views_view_unformatted(&$vars) {
  foreach ($vars['rows'] as $id => $row) {
    if ($vars['view']->result[$id]->node_sticky == 1) {
      $vars['classes'][$id] .= ' sticky';
    }
  }
}
After adding the above code in template.php , don't forget to flush all caches, or Drupal won't notice the addition!

The above works admirably, though you should node a couple of things:

  • the hook invoked is for the unformatted view style
  • in order to have the node_sticky element you need to add the Node: Sticky field
  • in order not to appear with the actual printable output, you should exclude the field from view

You can obviously add conditions for classes based on any field you have included in your view, eg for nodes being unpublished.