Adding classes to nodes based on their view modes
Happy holidays! After a few days off, it's back to Drupal theming for me. Today I noticed that adding a class to the node element with the view mode would make theming a particular site significantly easier, because of some contextual features in the design. The core node module adds node-teaser by default, but there's no class on the full node or other view modes to distinguish them. I decided to add one via preprocess-node.inc, like so:
<?php
function MYTHEME_alpha_preprocess_node(&$variables) {
$variables['attributes_array']['class'][] = 'node-' . $variables['view_mode'];
}
The result: A nice node-full class when viewing the full node, and a similar class for all my other view modes.
However, this added a double node-teaser because the default class was still there. To clean it up, I added an if statement to prevent the extra class from being added in teaser mode. Here's the result:
<?php
function MYTHEME_alpha_preprocess_node(&$variables) {
if ($variables['view_mode'] != 'teaser') {
$variables['attributes_array']['class'][] = 'node-' . $variables['view_mode'];
}
}
I've left the <?php at the beginning for any preprocessing newbies. This only has to be added to a preprocessing file once, and you don't need to close it, just open it. As always, change MYTHEME to your theme name.
Other Base Themes
This is for Omega, since Omega's what I've been using recently. If you want to do this for another theme, you'll probably need to replace the attributes array with a classes array, like so: $variables['classes_array'][] = 'node-' . $variables['view_mode'] I haven't tested this, but it's based on the last submitted patch on a core feature request to always pass the view mode as a class.
You may need to place it in template.php instead, and lose "alpha_" from the function name.