Sharing templates between multiple Drupal views
Do you have multiple views on your Drupal site, where the content listing is themed to look exactly the same? For example, say you have a custom "search this site" view, a "featured articles" view, and an "articles archive" view. They all show the same fields — for example, "title", "image", and "summary". They all show the same content types – except that the first one shows "news" or "page" content, whereas the others only show "news".
If your design is sufficiently custom that you're writing theme-level Views template files, then chances are that you'll be in danger of creating duplicate templates. I've committed this sin on numerous sites over the past few years. On many occasions, my Views templates were 100% identical, and after making a change in one template, I literally copy-pasted and renamed the file, to update the other templates.
Until, finally, I decided that enough is enough – time to get DRY!
Being less repetitive with your Views templates is actually dead simple. Let's say you have three identical files – views-view-fields--search_this_site.tpl.php
, views-view-fields--featured_articles.tpl.php
, and views-view-fields--articles_archive.tpl.php
. Here's how you clean up your act:
- Delete the latter two files.
- Add this to your theme's
template.php
file:<?phpfunction mytheme_preprocess_views_view_fields(&$vars) { if (in_array( $vars['view']->name, array( 'search_this_site', 'featured_articles', 'articles_archive'))) { $vars['theme_hook_suggestions'][] = 'views_view_fields__search_this_site'; }}
- Clear your cache (that being the customary final step when doing anything in Drupal, of course).