There's more than one way to Drupalise a cat

May 13, 2016

One of the components in the new design for The Gallery Guide is something I’m calling tiles - as always, naming things is one of the hardest parts.

The component includes an image with a transparent overlay, showing the title. On hover and focus, some extra information becomes visible. For instance, for a gallery, the address will be shown, and for an exhibition, the artists and tags will be shown. Here’s a Codepen which gives you an idea:

See the Pen Tiles... by malcomio (@malcomio) on CodePen.

Different versions of this component are used in quite a few places. On an exhibition page, it applies to a teaser view of the gallery linked via a node reference field. In various views, it applies to the views fields. To get the markup right for the views fields, I needed to create a custom template. But I didn’t want to create the same template for each view that needed to use the tile pattern - that would be a nightmare to maintain.

Having read about Twig template extends I was tempted to try them for this use case - it seems like an interesting new feature, so why not try it out?

I created an initial template called views-view-fields--tiles.html.twig, and then set the view template to use it. For instance, I wanted to apply this markup for the exhibitions_new view, so I created a template called views-view-fields--exhibitions-new.html.twig, which contained just one line:

{% extends "themes/gall/templates/views/views-view-fields--tiles.html.twig" %}

It seemed to work OK, but didn’t seem like the right approach. For one thing, it would leave me with a theme cluttered with loads of one-line templates, which would get pretty annoying pretty quickly. For another, it felt like a gratuitous use of a solution - a hammer looking for some nails to bash.

The solution I went with in the end was much more familiar from previous Drupal versions, although it uses the new hook_theme_suggestions_HOOK_alter hook:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function gall_theme_suggestions_views_view_fields_alter(array &$suggestions, array $variables) {
  // Set up views to use the tiles template.
  $tiles_views = array(
    'exhibitions',
    'exhibitions_a_z',
    'exhibitions_new',
    'exhibitions_this_gallery',
    'galleries_a_z',
    'galleries_new',
  );
  $view_id = $variables['view']->id();
  if (in_array($view_id, $tiles_views)) {
    $suggestions[] = 'views_view_fields__tiles';
  }
}

For someone familiar with previous versions of Drupal, it’s another thing which is similar but different. More to learn, and some things to unlearn, but we’re not starting from scratch, and we can have more options in our toolkit.