Drupal 7 Themes: Dynamic Theming

Exclusive offer: get 50% off this eBook here
Drupal 7 Themes

Drupal 7 Themes — Save 50%

Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling

$23.99    $12.00
by Ric Shreves | July 2011 | Drupal Open Source PHP Web Development

The Drupal system, backed by the powerful PHPTemplate engine, gives you the ability to create logic that will automatically display templates or specific page elements in response to the existence of certain conditions. This article by Ric Shreves, author of Drupal 7 Themes, reviews different techniques available for creating templates that are responsive to the conditions on the screen.

Among the techniques covered in this article are:

  • Working with the Administration theme
  • Using template suggestions to control display by page, node, or block

 

Drupal 7 Themes

Drupal 7 Themes

Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling

        Read more about this book      

(For more resources on Drupal, see here.)

Designating a separate Admin theme

Let's start with one of the simplest techniques, that is, designating a separate theme for the use of your admin interface. The Drupal 7 system comes bundled with the Seven theme, which is purpose-built for use by the administration interface. Seven is assigned as your site's admin theme by default. You can, however, change to any theme you desire.

Changing the admin theme is done directly from within the admin system's Theme Manager. To change the admin theme, follow these steps:

  1. Log in and access your site's admin system.
  2. Select the Appearance option from the Management menu.
  3. After the Theme Manager loads in your browser, scroll down to the bottom of the page. You can see at the bottom of that page a combo box labeled Administration theme, as shown in the following screenshot.
  4. Select the theme you desire from the combo box.
  5. Click Save configuration, and your selected theme should appear immediately.

The Administration theme combo box will display all the enabled themes on your site. If you don't see what you want listed in the combo box, scroll back up, and make sure you have enabled the theme you desire. If the theme you desire is not listed in the Theme Manager, you will need to install it first!

Additionally note the option listed below the Administration theme combo box: Use the administration theme when editing or creating content. Though this option is enabled by default, you may want to de-select this option. If you de-select the option, the system will use the frontend theme for content creation and editing. In some cases, this is more desirable as it allows you to see the page in context, instead of inside the admin theme. It provides, in other words, a more realistic view of the final content item.

Using multiple page templates

Apart from basic blog sites, most websites today employ different page layouts for different purposes. In some cases this is as simple as one layout for the home page and another for the internal pages. Other sites take this much further and deliver different layouts based on content, function, level of user access, or other criteria. There are various ways you can meet this need with Drupal. Some of the approaches are quite simple and can be executed directly from the administration interface; others require you to work with the files that make up your Drupal theme.

Creative use of configuration and block assignments can address some needs. Most people, however, will need to investigate using multiple templates to achieve the variety they desire. The bad news is that there is no admin system shortcut for controlling multiple templates in Drupal—you must manually create the various templates and customize them to suit your needs. The good news is that creating and implementing additional templates is not terribly difficult and is it possible to attain a high degree of granularity with the techniques described next. Indeed should you be so inclined, you could literally define a distinct template for each individual page of your site!

While there are many good reasons for running multiple page templates, you should not create additional templates solely for the purpose of disabling regions to hide blocks. While the approach will work, it will result in a performance hit for the site, as the system will still produce the blocks, only to then wind up not displaying them for the pages. The better practice is to control your block visibility through the Blocks Manager.

Drupal employs an order of precedence, implemented using a naming convention. You can unlock the granularity of the system through proper application of the naming convention. It is possible, for example, to associate templates with every element on the path, or with specific users, or with a particular functionality or node type—all through the simple process of creating a copy of the existing template and then naming it appropriately.

In Drupal terms, this is called creating template suggestions.

When the system detects multiple templates, it prefers the specific to the general. If the system fails to find multiple templates, it will apply the relevant default template from the Drupal core.

The fundamental methodology of the system is to use the most specific template file it finds and ignore other, more general templates. This basic principle, combined with proper naming of the templates, gives you control over the template that will be applied in various situations.

The default suggestions provided by the Drupal system should be sufficient for the vast majority of theme developers. However, if you find that you need additional suggestions beyond those provided by the system, it is possible to extend your site and add new suggestions. See http://drupal.org/node/190815 for an example of this advanced Drupal theming technique.

Let's take a series of four examples to show how this system feature can be employed to provide solutions to common problems:

  1. Use a unique template for your site's home page
  2. Use a different template for a group of pages
  3. Assign a specific template to a specific page
  4. Designate a specific template for a specific user

Creating a unique home page template

Let's assume that you wish to set up a unique look and feel for the home page of a site. The ability to employ different appearance for the home page and the interior pages is one of the most common requests web developers hear.

There are several techniques you can employ to achieve the result; which is right for you depends on the extent and nature of the variation required, and to a lesser extent, upon the flexibility of the theme you presently employ. For many people a combination of the techniques will be used.

Another factor to consider is the abilities of the people who will be managing and maintaining the site. There is often a conflict between what is easiest for the developers and what will be easiest for the site administrators. You need to keep this in mind and strive to create manageable structures. It is, for example, much easier for a client to manage a site that populates the home page dynamically, then to have to create content in multiple places and remember to assign things in the proper fashion. In this regard, using dedicated templates for the home page is generally preferable.

One option to address this issue is the creative use of configuration and assignment. You can achieve a degree of variety within a theme—without creating dedicated templates—by controlling the visibility and positioning of the blocks on the home page.

Another option you may want to consider is using a contributed module to assist with this task. The Panels and Views modules in particular are quite useful for assembling complex home page layouts. See Useful Extensions for Themers for more information on these extensions.

If configuration and assignment alone do not give you enough flexibility, you will want to consider using a dedicated template that is purpose-built for your home page content.

To create a dedicated template for your home page, follow these steps:

  1. Access the Drupal installation on your server.
  2. Copy your theme's existing page.tpl.php file (if your theme does not have a page.tpl.php file, then copy the default page.tpl.php file from the folder /modules/system).
  3. Paste it back in the same directory as the original file and rename it page--front.tpl.php.
  4. Make any changes you desire to the new page--front.tpl.php.
  5. Save the file.
  6. Clear the Drupal theme cache.

That's it—it's really that easy. The system will now automatically display your new template file for the site's home page, and use the default page.tpl.php for the rest of the site.

Note that page--front.tpl.php will be applied to whatever page you specify as the site's front page using the site configuration settings. To override the default home page setting visit the Site Information page from the Configuration Manager. To change the default home page, enter the path of the page you desire to use as the home page into the field labeled Default home page.

Next, let's use the same technique to associate a template with a group of pages.

The file naming syntax has changed slightly in Drupal 7. In the past, multiple words contained in a file name were consistently separated with a single hyphen. In Drupal 7, a single hyphen is only used for compound words; a double hyphen is used for targeting a template. For example, page--front.tpl.php uses the double hyphen as it indicates that we are targeting the page template when displayed for the front page. In contrast, maintenance-page.tpl.php shows the single hyphen syntax, as it is a compound name.

Remember, suggestions only work when placed in the same directory as the base template. In other words, to get page--front.tpl.php to work, you must place it in the same directory as page.tpl.php.

Using a different template for a group of pages

You can provide a template to be used by any distinct group of pages. The approach is the same as we saw in the previous section, but the name for the template file derives from the path for the pages in the group. For example, to theme the pages that relate to users, you would create the template page--user.tpl.php.

A note on templates and URLs
Drupal bases the template order of precedence on the default path generated by the system. If the site is using a module like Pathauto, that alters the path that appears to site visitors, remember that your templates will still be displayed based on the original paths. The exception here being page--front.tpl.php, which will be applied to whatever page you specify as the site's front page using the site's Configuration Manager.

The following table presents a list of suggestions you can employ to theme various pages associated with the default page groupings in the Drupal system:

Drupal 7 Themes: Dynamic Theming

The steps involved in creating a template-specific theme to a group of pages is the same as that used for the creation of a dedicated home page template:

  1. Access the Drupal installation on your server.
  2. Copy your theme's existing page.tpl.php file (if your theme does not have a page.tpl.php file, then copy the default page.tpl.php file from the folder /modules/system).
  3. Paste it back in the same directory as the original file and rename it as shown in the table above, for example page--user.tpl.php.
  4. Make any changes you desire to the new template.
  5. Save the file.
  6. Clear the Drupal theme cache.

Note that the names given in the table above will set the template for all the pages within the group. If you need a more granular solution—that is, to create a template for a sub-group or an individual page within the group, see the discussion in the following sections.

Assigning a specific template to a specific page

Taking this to its extreme, you can associate a specific template with a specific page. By way of example, assume we wish to provide a unique template for a specific content item. Let's assume the page you wish to style is located at http://www.demosite.com/node/2. The path of the page gives you the key to the naming of the template you need to style it. In this case, you would create a copy of the page.tpl.php file and rename it to page--node--2.tpl.php.

Using template suggestion wildcards
One of the most interesting changes in Drupal 7 is the introduction of template suggestion wildcards. In the past, you would have to specify the integer value for individual nodes, for example, page--user--1.tpl.php. If you wished to also style the pages for the entire group of users, you had the choice of either creating page--user.tpl.php, that affects all user pages, including the login forms, or you would be forced to create individual templates to cover each of the individual users. With Drupal 7 we can now simply use a wildcard in place of the integer values, for example, page--user--%.tpl.php. The new template page--user--%.tpl.php will now affect all the individual user pages without affecting the login pages.

Designating a specific template for a specific user

Assume that you want to add a personalized theme for the user with the ID of 1 (the first user in your Drupal system, and for many sites, the ID used by the super user). To do this, copy the existing page.tpl.php file, rename it to reflect its association with the specific user, and make any changes to the new file. To associate the new template file with the user, name the file: page—-user--1.tpl.

Now, when the user with ID=1 logs into the site, they will be presented with this template. Only user 1 will see this template and only when he or she is logged in and visiting the user page.

Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling
Published: May 2011
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:
        Read more about this book      

(For more resources on Drupal, see here.)

Dynamically theming page elements

In addition to being able to style particular pages or groups of pages, Drupal makes it possible to provide specific styling for different page elements.

Associating elements with the front page

Drupal provides $is_front as a means of determining whether the page currently displayed is the front page. $is_frontis set to true if Drupal is rendering the front page; otherwise it is set to false.

We can use $is_front in our page.tpl.php file to help toggle the display of items we want to associate with the front page. To display an element on only the front page, make it conditional on the state of $is_front. For example, to display the site slogan on only the front page of the site, wrap $site_slogan (in your page.tpl.php file) as follows:

<?php if ($is_front): ?>
<?php print $site_slogan; ?>
<?php endif; ?>

To set up an alternative condition, so that one element will appear on the front page but a different element will appear on other pages, modify the statement like this:

<?php if ($is_front): ?>
//whatever you want to display on front page
<?php else: ?>
//what is displayed when not on the front page
<?php endif; ?>

$is_front is one of the default baseline variables available to all templates. Other useful baseline variables include $is_admin, that returns true when the visitor is a site administrator and $logged_in, that returns true when the viewer is a member of the site, logged in and authenticated. The entire list of baseline variables is documented inside your page.tpl.php file.

Styling by region

The region.tpl.php file is new in the core of Drupal 7. The file provides a template that is used for the regions on your site and contains within it the output of the block.tpl.php template.

As this file is used for all regions on the site, it is unlikely you will ever want to override this template globally. However, it is conceivable that at some point you may want to provide a template for one or more of your specific regions. To provide a template suggestion targeting one of the regions on your site, you must first copy the region.tpl.php file to your theme directory, then copy it and rename it to provide the template suggestion. The proper syntax for a suggestion targeting a region is: region--region-name.tpl.php, for example, region--sidebar-first.tpl.php.

Dynamically styling blocks

By default, the system's block output is controlled by the block.tpl.php template. The template can be overridden or intercepted with a variety of template suggestions. As we have seen in other areas, PHPTemplate will look to the names given multiple template files to determine which template to display. The order of precedence used for the block template is consistent with that used elsewhere.

At the most specific, you can provide a template to apply to the blocks of a specific module of a specific delta (block--module-name--delta.tpl.php). You can also attach a template to all the blocks generated by a module (block--module-name.tpl.php), or to the blocks assigned to a particular region (block--region-name.tpl.php). Failing the presence of any of these, the system applies the default block.tpl.php template.

Drupal 7 Themes: Dynamic Theming

Note that the order of precedence includes the name of the module that produces the output being displayed in the block. Delta is a system-generated value that provides a unique identifier for each block.

All blocks manually created by the user share the module name "block".

If you are not certain of the provenance of your block, that is, the name of the module that produces the block or the block's delta, try using the Theme Developer feature of the Devel module. If you have the Devel module installed on your site, you can harvest this information in the form of a list of suggestions quite easily. To use this feature:

  1. Install the Devel module.
  2. Install the Theme Developer module.
  3. Enable both modules.
  4. Open your browser and go to the page where your block appears.
  5. Click the Themer Info checkbox on the bottom-left of the screen, then click on the block in question.

When you click on the element, a pop up will appear, such as the one in the following illustration:

Looking at the preceding screenshot you can see the suggestions relevant to the block in our exam:

Drupal 7 Themes: Dynamic Theming

Summary

This article covers the basics needed to make your Drupal theme responsive to the contents and the users. By applying the techniques discussed in this article, you can control the theming of pages based on content, state of the pages, or the users viewing them. Taking the principles one step further, you can also make the theming of elements within a page conditional. In the next article will be on Creating Dynamic CSS Styling. The ability to control the templates used and the styling of the page and its elements is what we call dynamic theming.


Further resources on this subject:


Drupal 7 Themes Create new themes for your Drupal 7 site with a clean layout and powerful CSS styling
Published: May 2011
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Ric Shreves

Ric Shreves is a web applications consultant and tech author. He’s been building websites since the mid-90s and writing about tech for almost as long. Ric specializes in open source content management systems and has written texts on each of the big three: WordPress, Joomla! and Drupal.

Ric is the founding partner of water&stone, a digital agency that focuses on new media and online marketing. He works with clients on digital marketing strategy and supervises the SEO implementation team. Ric lives in Bali and divides his time between the island and Singapore.

Books From Packt


Drupal 7
Drupal 7

Drupal 7 Fields/CCK Beginner's Guide
Drupal 7 Fields/CCK Beginner's Guide

Drupal 7 Module Development
Drupal 7 Module Development

Drupal Intranets with Open Atrium
Drupal Intranets with Open Atrium

Drupal 6 Panels Cookbook
Drupal 6 Panels Cookbook

Drupal E-commerce with Ubercart 2.x
Drupal E-commerce with Ubercart 2.x

Drupal 6 Performance Tips
Drupal 6 Performance Tips

Drupal Web Services
Drupal Web Services


No votes yet

Post new comment

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
F
h
h
X
s
q
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software