March 25, 2015

March 25, 2015
In this article, we are going to discuss about How to rewrite the Drupal views output for custom theming and CSS. 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.

0 comments:

Post a Comment