Drupal 7 Custom Theming Strategies in Context

Let me start by stating that I came into drupal thinking template overrides and adding/removing divs, classes and regions within the template files was the most important thing to know in order to theme in drupal. I have since learned that most of the work can be done through configuring within the administrative interface as well as by utilizing the default div’s and classes in your CSS.

Overriding a template should only be done when you need major, site-wide structural changes to a page’s, node’s, or block’s template file such as adding or removing regions because the changes will apply to ALL use-cases of those files. Smaller, less structural – but still site wide – changes can be applied through theme functions and lastly, fine-tuned and case specific changes can be applied through theme hook suggestions. But that’s just the tip of the iceberg for all the theming strategies available to you.

These kinds of distinctions are exactly what I am trying to clarify in this overview comparing the many, many different theming strategies used by Drupal Themers and discussed in the books “The Definitive Guide to Drupal 7,” by Melancon et al (which the page #’s reference) and I must also mention, “Beginning Drupal 7″ by Todd Tomlinson although to a much lesser extent.

I am told that as an open source system, there are no hard and fast rules for using one technique over another in any given circumstance so my goal is to organize everything as best as possible into an easy to understand context in order to compare and develop well-informed personal preferences and strategies. That is, I am more interested in the when and why rather than the how.

I’m still learning Drupal and began compiling this information as a study guide rather than as a knowledgeable expert in the field, so if anyone out there can offer any suggestions or elaborate on the information here, particularly in the list of most common/practical examples offered for each technique, feel free to comment below or go to my new drupal group Students of Drupal to improve the wiki (and become a member!).

Modifying Contents, Structure, and Placement of Elements

  • The Basic page content type provides you with a text field for entering the title of the content item, and a body text area. The body field is flexible and can contain whatever the author feels like writing about.
    • Write an entire book in the body field, including HTML markup (headings, tables, CSS, and so on).
    • Insert pictures.
    • Write a single sentence.
  • An article is identical to a basic page with the single exception that an article has an image upload feature and an additional field where the author can enter what are called tags. Tags are simply words that help classify, organize, and search for related content on your site.
  • Custom Content Types and Fields are good when you want to:
    • Require that certain information is entered before the author submits the content item for publishing; for example the start date and time for an event, the address of the venue where the event is being held, and a link to the event on a Google map.
    • Have the ability to perform calculations based on the information that is captured in a content item.
    • Have the ability to sort content items by specific “fields.”
    • Have the ability to “filter” or restrict which content items are displayed on a page based on a value in a field.
    • Enforce the structure of how a piece of content is rendered on a page; for example, you may want to display information about a book and want the title to be followed by the author, followed by the ISBN, followed by the price, followed by the description of the book.
  • A block is a generic term that is applied to any self-contained piece of content, menu, or code and which are assigned to a region in structure > blocks. Standard blocks that come with Drupal include the login block, the search block, the “who’s online” block, the “who’s new” block, the latest blog postings block, and more. There are also blocks that come with contributed modules, such as blocks that share the latest weather report, your recent Twitter posts, or your current Facebook status. As a site administrator, you can construct your own custom blocks
  • Views provides an easy-to-use tool for selecting and displaying lists of content on your website. It is essentially a smart query builder that can build the proper query, execute it, and display the results. Examples of how you might use Views include:
    • Displaying the most recent news articles posted to your website, sorted in descending order by the date of posting.
    • Displaying a list of company locations as a table that is sortable by clicking on the titles for the location name, city, state, and country.
    • Displaying a list of blog postings that is filterable by subject.
    • Creating an RSS feed that lists the most recent content posted on your website.
    • Displaying just about any kind of list that you can think of, created from the content that is stored on your website, as a list, table, or RSS feed.
  • Panels are useful when you want to divide a region into multiple “mini-regions” called panel panes. *
  • Alter Hooks (p 323), ex: dynamically add HTML for new small bit of content into a region, moving content from one region to another based on certain circumstances, and changing the contents of tabs based on certain circumstances. **
  • render(), hide(), and show() (p 327), selectively renders bits of content, such as fields, inside theme functions, templates and pre/process functions. Ex: render() is essentially an implementation of a render array **, hiding part or all of a render element to allow them to be placed outside of a div, hiding content based on certain circumstances, show() reverts a previously applied hide(), render() can be used multiple times. ***

* Views can be used with panel panes to define what content should be rendered, how many items should be included in the list, and how those items should be rendered. Using Taxonomy, content authors select the appropriate taxonomy term that is associated with each panel pane, and the content automatically appears in the right spot on the right page.

** Render Arrays are structered arrays that contain nested data and other information that drupal uses to render HTML (p 321) they are similar to theme hooks in that they use template and theme functions but they are modified using alter hooks (323).

***It’s best to do these operations in preprocess or process functions in order to keep your templates clean and more manageable (329).

Styling

  • Define Stylesheets via the .info file (p 343), to be loaded for all pages
  • drupal_add_css() to conditionally load stylesheets (p 344), ex: to dynamically print as an “inline” block of css code within the <head> tag, stylesheets for single pages, specifying the weight of a file to control the order that it loads, conditional stylesheets that target specific browsers, loading external stylesheets, excluding a CSS file from the aggregation and compression process. *
  • hook_css_alter() to remove or override CSS files provided by modules and core (p 345).

*Enabling aggregation and compression for CSS files (admin/config/development/performance) on all live sites is highly recommended, as it will speed up page loads quite a bit (341).

Adding, Removing and Modifying Variables

  • Preprocess Functions (p 314) are normally used to add or tweak variables* available inside template files, for example to provide the $subject variable in block.tpl.php. Ex: dynamically adding CSS classes to variables (such as regions) as opposed to overriding a template, hiding links in certain situations, modifying the portion of content that is to be viewed in certain situations, and to create a custom variable to input a link for a type of user (318). **
  • Process Functions (p 314) ex: adding, removing, hiding, and modifying variables in certain circumstances “later in the processing cycle.” **

*use devel module’s dpm() function to determine all the available variables to work within each theme hook p.311

** These functions are run prior to the template being displayed, thereby allowing you to manipulate the variables for use in the templates themselves.

Modifying HTML Markup

  • Theme Hook Suggestions p.305 – progressively traverse drupal’s template/theme function/block specificity to target a specific template/theme function/block for one-off specific changes.
  • Template** Overrides p.293 – major site-wide changes to structure of a page, nodes, blocks, or to add/remove regions*** (291)

*These are theme specific, meaning if the site employs more than one theme it will not apply.
** The block.tpl.php file, for example, is used when a block is being rendered. Template files can be overridden by copying them into your own theme. It is also possible to make specific overrides with naming conventions, such as block–user.tpl.php.

*** Regions play a large part in defining the high-level structure of HTML markup. Typical regions include the header, footer, sidebars, and content, most of a site’s content is output inside these regions.

Drupal 7 Introduction and Custom Theming

Its been almost 2 weeks since my last semester ended and I intended to take some time off to relax and read “Smashing CSS” by Eric Meyer. That only took me 2 days and I had started to play around with the idea of rebuilding the website of the non-profit that I intern at with cleaner, more standards compliant code and implementing php includes to centralize the common areas such as the header, navigation, and footer for easy modifications and redesigns when I came across the Drupal 7 content management system. Even though I’ve read that this framework is complex and has a learning “cliff,” I decided that this was a valuable skill to acquire and that it would help the people at the non-profit that I intern at who don’t know very much about web design and sometimes struggle with content updates on their website. So, in case anybody would like to follow along and avoid the sometimes frustrating lack of straightforward online tutorials on implementing a local testing server and setting up drupal I will provide the most winning tutorials that I have found throughout the past week and a half.

In order to download and install MAMP, a free local testing server software, and implement it so the url will read http://mysite.com instead of something ugly like http://localhost:8080/mysite.com I found a simple and straightforward tutorial at

Set Up Your MAMP Like a Dev King

Although there was a problem modifying the hosts file so I did a search and found this tutorial that showed me how to do that through the terminal:

How to edit the hosts file in Mac OS X – Leopard

Next, I needed to set up a MySQL database in MAMP, change the default username and password, and than download Drupal on it:

Changed The Root Password

Setting Up MySQL Database and Connecting WP Account

I had read that there were certain contributed modules that are considered must-have and that it was necessary to increase memory limit for PHP in MAMP for them, so I did that with this tutorial:

HowTo: Create a local environment using MAMP

Update 02/06/2012:

After several months of trying to figure out my own path to becoming competent in Drupal from the position of  learning how to customize with a precision knife and paining over learning pre/process functions, template overrides, theme hook suggestions etc with only a very basic idea of how to configure, I now realize that it is nearly impossible to learn how to theme in drupal without first learning how to configure the various content types using core and contributed modules. Its amazing how much can be done with configuration without getting into the code and besides, its just best practice in my opinion to configure rather than code when the option is available. Johan Falk of NodeOne has made the most comprehensive drupal video tutorials available for free. I recommend watching the following screencasts in order:

Learning Drupal 7 with NodeOne

Taming the Beast: Learn Views with NodeOne

You should be well into your own Drupal project at this point because the use cases of the following tutorials are very particular and use several modules in conjunction with each other, which is all very hard to wrap your head around on a purely theoretical level.

Learn Relation Module with NodeOne

Learn Page Manager with NodeOne

Johan has compiled many of his screencasts into the Four Weeks of Drupal series, which more specifically includes a chapter on theming in Drupal. If you followed the order of my tutorial advice you should have already started  your own drupal-based website. You should start theming only after you’ve configured a primary page or two such as a home page or interior pages that are going to be unique from the rest of the  pages.

Other great modules that are supposed to revolutionize and make it a lot easier to theme without getting your hands dirty with code are the Display Suite, Fieldgroup, and Beans modules however Tim Cosgrove’s BadCamp presentation on these only served to confuse me and I haven’t found any tutorials on the Fieldgroup or Beans modules. I did find a tutorial on Display Suite by swentieman

I haven’t read Johan Falk’s book, “Drupal 7: The Essentials,” but judging from his video tutorials and what I’ve seen in other books, its probably one of the best books for beginning Drupal and I feel totally confident in recommending it. If you buy only one book however, it definitely has to be “The Definitive Guide to Drupal 7“.