Rewriting Drupal Views Output for Custom Theming & CSS


I love it when we discover one of those wonderful Drupal gems that is not well documented and is very powerful in creating some nice Drupal Views theme customization. We were recently tasked with creating an events calendar that has a custom CCK field called "City". There's a drop down menu with a list of cities to assign the event to. So along with an event listing, you also see a city such as New York or Boston. The client wanted these cities to be color coded.

The issue was, how to assign the color to the city with CSS using Views. We tried a custom View theme template but this got us nowhere as there seemed to be no way to out put the names of fields.

Finally we hit upon it, there is an option in Views under Fields called "Rewrite the output of this field". When you click on a field to edit and select the checkbox for this option, you are presented with possible "Replacement patterns". In our case, we used the city location field as our CSS selector for the city location.

Here is our custom output rewrite code we used:

<div class=[field_event_location_value]>[field_event_location_value]</div>
The HTML output for the above is:
<div class="Boston">Boston</div>
We can now create a custom CSS class for Boston like this:
.page-events .Boston {
color:#2B0082;
}

Note that to utilize this properly you can only use fields that have come before the one you are currently working on so you may need to just rearrange the order or add a field but select "Exclude from display" just to get the data in to be available for use.

The possibilities for uses for Drupal Views Output Rewriting are endless and we are already using it for many different purposes for custom Views theming.

Tags