Understanding the Drupal Way - Specificity

Submitted by Marc on Mon, 12/14/2015 - 12:01pm

In the post on making output themeable I discussed the example of overriding a template file for a flag. The template file I overrode was a generic definition of the markup for all the flags on a site. I can create a template file that overrides a specific flag.

To begin, I create a new flag. Let's say that the machine name is theme_this_flag. Then I attach that flag to my desired content type(s). I create a piece of content using (one of) the content type(s). If I look at that piece of content using the default Bartik theme I see that it has no special styling on the flag. Once I change my theme to my custom Bartik subtheme I see that the flag has a colored background as well as a dotted line below it.

If I look at a different piece of content that uses different flags, I see that the flags do not have the dotted line. This is because the flags on that piece of content are using the generic template file to generate the markup.

The flag on my new content type's piece of content uses the more specific template that applies to that flag.

Look at the names of the two template files inside of my custom subtheme. flag--theme_this_flag.tpl.php is responsible for this more specific markup. In addition to using a wrapping div with the theme-me class, I have added the i-am-special class. I am using CSS to target that class and add the dotted line to the presentation of the flag.

The machine name of my new flag, theme_this_flag, is the "key" that I used to create a more specific template file for just this flag. The special flag is attached only my desired content type(s).

This is just one example of how Drupal uses specificity, but it gives the general idea of how it works in all the other cases as well.

If you want to learn more about Drupal, you can take my "Drupal for Beginners" class for just $5.