Home Web Development Drupal 6 Theming Cookbook

Drupal 6 Theming Cookbook

By Karthik Kumar , Dries Buytaert
books-svg-icon Book
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $28.99 $19.99
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Drupal Theme Basics
About this book
Themes are among the most powerful features that can be used to customize a website to fit your needs. The greatest strength of Drupal lies in its design, which, when done right, allows developers to customize every aspect of the site. Although it might sound easy to customize the look of your site, it's not a cakewalk to build custom themes that are easy to administer and maintain.Drupal 6 Theming Cookbook provides a plethora of recipes that enable Drupal template designers to make full use of Drupal's extensibility and style their site just the way they want it. It is a well-rounded guide, which will allow users looking to theme their Drupal sites to do so by taking full advantage of Drupal's theming system. It covers numerous aspects from creating custom themes to using the powerful CCK, Views, and Panels modules to create rich designs that are easy to administer and maintain.Structured as a collection of recipes to perform a wide variety of tasks, this book will guide readers through most important aspects of Drupal theming. It starts off with recipes dealing with the basics of Drupal's theme system: you will find recipes for solving all your problems with regions and blocks. It then moves on to advanced topics such as creating a custom theme and using it to modify the layout and style of the content that is output on a page. A substantial number of recipes are dedicated to Drupal's template system, which will provide you with a solid foundation in order to override the output of Drupal and contributed modules. Furthermore, as the combination of modules such as CCK, Views, and Panels is so widely prevalent, chapters have been dedicated for each of these modules. With this book, you'll learn to get the most out of Drupal's templating system and its modules to create rich designs for your site.
Publication date:
November 2010
Publisher
Packt
Pages
384
ISBN
9781847198686

 

Chapter 1. Drupal Theme Basics

We will be covering the following recipes in this chapter:

  • Installing and enabling a theme

  • Uploading a new logo

  • Uploading a new favicon

  • Adding a slogan to the theme

  • Allowing users to choose from multiple themes

  • Displaying a different theme for administration

  • Adding an existing block to the theme

  • Adding a custom block to the theme

  • Displaying a block only on the front page

  • Controlling block visibility based on user role

  • Controlling block visibility based on node type

 

Introduction


Drupal is designed to separate logic from presentation with the former usually handled through the use of modules and the latter via themes. Although this separation is not absolute, it is distinct enough to facilitate quick and efficient customization and deployment of websites. This especially holds true when the site is developed in a team environment as it enables developers, designers, and content managers to work independently of each other.

Themes are synonymous with skins in other applications and control the look and feel of a website. Each theme can consist of a variety of files ranging from a .info configuration file which registers the theme with Drupal to .tpl.php template files accompanied by CSS, JavaScript, and other files that determine the layout and style of the content. Depending on the nature of the site and its requirements, developers can choose from the slew of themes available on http://drupal.org as contributed themes or, instead, decide to roll their own.

Contributed themes are, as the name suggests, themes which have been contributed by the Drupal community at large. They usually tend to be the designs that have been developed by a user for a site and then shared with the community, or designs from other packages or sites which have been ported over to Drupal. Consequently, while they are ready-to-wear, they are generic in nature and lack uniqueness. Furthermore, the quality of these themes vary significantly from one to the other with some being excellent and others well below par. Contributed themes are primarily used for sites which require rapid deployment or in hobby sites with basic requirements where uniqueness is not a factor.

Custom themes, on the other hand, are a necessity for sites with unique requirements in layout, usability, and design. While they are often built from the ground up, it is now established practice to use special starter themes as a base on which they can be extended.

Contributed themes can be accessed at http://drupal.org/project/themes. This page, by default, lists all available themes and provides filters, to narrow down on those which are compatible with Drupal 6, and sorting options to peruse contributions based on popularity, update status, and other criteria. More information about a particular theme can be accessed by clicking on its Find out more link.

Prior to choosing a contributed theme, there are a few considerations to keep in mind. Firstly, it is important to have a general idea of the layout required for the site with the chief concern usually being the column layout of the theme. Most themes support a three-column (with two sidebars and a content area) layout which also work as two-column layouts (one sidebar) if no content is added to one of the sidebars. The more exotic ones support four or more columns and are only really a viable option for special cases.

Secondly, while fewer themes nowadays are being laid out using tables, they are still around. Unless there is no other recourse, these should be avoided in favor of CSS layouts.

Next, check to see whether the theme is a fixed-width or a fluid theme or supports both types. Fixed-width themes, as the name suggests, maintain a predefined width irrespective of the user's screen resolution. As a result, the site has a consistent appearance. Fluid layouts, or liquid layouts as they are sometimes referred to, grow according to the user's screen size and consequently make better use of the available real estate. The question of which to use is generally decided on a case by case basis.

The Drupal theme system also supports the use of different theme engines to render the design. Each engine uses a different process by which the designer can interact with Drupal to implement a design. The PHPTemplate engine is built into Drupal and is by far the most popular of the ones available. The vast majority of contributed themes available are compatible with PHPTemplate. Nevertheless, it is prudent to check the specifications of the theme to ensure that it does not require a different theme engine. Contributed theme engines can, if necessary, be downloaded from http://drupal.org/project/theme+engines.

Every theme's project page usually provides screenshots and explicitly specifies layout and other useful information. A number of them also link to a demonstration page—as in the following screenshot—where the theme can be previewed and tested using different browsers, screen resolutions, and so on. A third-party site http://themegarden.org, which showcases various contributed themes, comes in very handy for the same reason.

Additionally, project pages customarily link to their CVS repositories where files within the theme can be viewed prior to downloading. It is also worth exploring the issue queue of a theme to see if bugs have been reported and are being addressed in a timely manner.

Note

CVS is a tool used by Drupal developers to manage their code and control their releases. It is effectively a repository for modules, themes, and Drupal itself. More information on CVS is available at http://drupal.org/handbook/cvs.

Once the list of candidate themes has been narrowed down to a short list, the only way to test them further is to download and install them. The theme project page lists available downloads based on version and stability along with release notes which might be useful to glance through as well. Download the latest release recommended for Drupal 6. The recipes in this chapter will address the installation and configuration of a downloaded theme.

 

Installing and enabling a theme


This recipe will cover the steps required to install and enable a downloaded theme.

Getting ready

Downloaded themes are usually in tar.gz format. These files can be extracted using archive programs such as 7-Zip (http://www.7-zip.org) as well as commercial packages such as WinZip (http://www.winzip.com) and WinRAR (http://www.rarlabs.com).

How to do it...

To install a theme, open Windows Explorer and navigate to the Drupal installation.

  1. Browse to sites/all and create a sub-folder named themes.

  2. Extract the downloaded theme into a sub-folder inside this folder. In other words, if the theme is called mytheme, the folder sites/all/themes/mytheme should contain all the files of the theme.

    In the last screenshot, we see the Acquia Marina theme's installation folder situated within sites/all/themes. Themes also occasionally contain a README.txt file which provides documentation which is worth a read-through.

    Tip

    File structure options

    In this recipe, we have chosen to use the folder sites/all/themes/mytheme to store our theme. By positioning our theme inside sites/all, we are stating that the theme is to be available to all sites using this Drupal installation. In other words, this enables multi-site setups to share modules and themes. In case we want to restrict access to the theme solely to one particular site, we would position its folder within sites/foo.example.com/themes/ where foo.example.com is the site in question.

  3. Access the Drupal site in a browser and navigate to admin/build/themes (Home | Administer | Site building | Themes).

  4. The newly installed theme should now be listed on this page. Check the associated Enabled checkbox and Default radio button.

In the last screenshot, we can see that the contributed theme Acquia Marina has been enabled and is set to be the default theme for the site. Drupal comes packaged with six core themes including Bluemarine shown in the last screenshot.

Click on Save configuration to enable the new theme and also set it as the default theme for the site.

How it works...

Drupal scans folders within sites/all/themes and, in particular, looks for files with the extension .info. This file contains information about the theme such as its name, description, version compatibility, and so on. If the theme is compatible, it is listed on the theme administration page.

A site can have multiple themes enabled. Out of these, only one can be chosen as the default theme. The default theme is, as the name suggests, the primary theme for the website. When more than one theme has been enabled, users with the select different theme permission can optionally select one of the other available options as their personal theme.

There's more...

Drupal makes it easier for us to manage our site by following preset naming conventions when it comes to the folder structure of the site.

Folder structure

Themes do not necessarily have to be placed at the root of the sites/all/themes folder. For organizational purposes, it might be useful to create sites/all/themes/contrib and sites/all/themes/custom. This will allow us to differentiate between downloaded themes and custom themes.

Tip

Since Drupal's core themes are located within the root themes folder, we might be led to believe that this might also be a good place to store our contributed or custom themes. While this will certainly work, it will prove to be a bad decision in the long run as it is never a good idea to mix core files with custom files. The chief reason for this separation is manageability—it is far easier to maintain and update Drupal when there is a clear distinction between the core installation, and contributed modules and themes.

 

Uploading a new logo


Most websites incorporate a logo into their design, usually accompanying the site name in the header. For example, the Drupal logo or "Druplicon" in the following screenshot represents the default logo displayed for every core theme that comes packaged with Drupal.

These logos tend to play an important role in the branding and identity of the site and are frequently an important facet in the overall design of the theme. This recipe details the steps involved in changing the logo displayed in a theme.

Getting ready

The new logo should be in a suitable format and should balance quality with size. The usual rule of thumb is as follows:

  • PNG: For high quality images which contain transparencies.

  • JPEG: For detailed photographic logos which do not involve transparencies.

  • GIF: For simple line-art.

How to do it...

Adding a custom logo to a theme can be done using the following steps:

  1. Navigate to admin/build/themes (Home | Administer | Site building | Themes).

  2. Click on the Configure link next to the theme in question.

  3. Look for the Logo image settings fieldset. Within, uncheck the Use default logo checkbox as we want to use a custom image.

  4. Using the Upload logo image field, browse and select the logo file in the filesystem.

  5. Finally, click on the Save configuration button below to upload and save the changes.

How it works...

The uploaded file is saved in the Drupal filesystem and the path to the logo is registered as a configuration setting in the database. During display, the theme uses this setting to embed the logo within the Drupal page. The following screenshot displays the Bluemarine core theme with its default logo replaced with a custom PNG.

There's more...

Besides specifying the logo file via a theme's configuration page, there are other avenues which can also be pursued.

Directly linking to image files

Alternatively, instead of uploading the logo via Drupal, use the Path to custom logo textfield to point to an existing logo file on the server. A third option is to just place the logo file in the theme's folder and rename it as logo.png. Provided that the Use the default logo field is checked, the theme will automatically look for this file in its folder and use it as its logo.

 

Uploading a new favicon


This recipe details the steps involved in changing the favicon displayed with the theme. A favicon, dubbed as a shortcut icon in the Drupal interface, is an image which is particular to a site and is displayed in the address bar of the browser next to the site URL as well as the browser tab. It also makes its presence felt if the site is bookmarked in the browser as in the following screenshot:

Getting ready

We are going to need the icon file to be added which is recommended to be of size 32x32 pixels or higher. An example icon file named favicon.ico can be seen in the misc folder in the Drupal installation.

How to do it...

Adding a custom favicon to the theme can be done by performing the following steps:

  1. Navigate to admin/build/themes (Home | Administer | Site building | Themes).

  2. Click on the Configure link next to the theme in question.

  3. Look for the Shortcut icon settings fieldset.

  4. Within, uncheck the Use default shortcut icon checkbox as we want to use a custom icon.

  5. Using the Upload icon image field, browse and select the icon file in the filesystem.

  6. Finally, click on the Save configuration button below to upload and save the changes.

How it works...

The uploaded file is saved in the Drupal filesystem and the path to the icon is registered as a theme setting in the database. When a page is being rendered, the Drupal theme system designates this .ico file as the favicon for the site.

In the following screenshot, we can see the logo image added in the previous recipe also being used as the basis for a favicon:

There's more...

Besides manually uploading the icon file via the theme's configuration page, other options exist to perform the same task.

Alternative methods

Alternatively, instead of uploading the icon file via Drupal, use the Path to custom icon textbox to point to the icon file on the server. A third option is to place the icon file in the theme's folder and rename it favicon.ico. Provided that the Use the default shortcut icon field is checked, the theme will automatically look for this file in its folder and use it as its favicon. Not specifying a favicon will result in the site using Drupal's default icon, Druplicon, instead.

Tip

Other formats besides the ICO format are also supported by some, but not all browsers. More information is available at http://en.wikipedia.org/wiki/Favicon#Browser_support.

 

Adding a slogan to the theme


This recipe details the steps involved in adding a slogan to the theme. Site slogans are a common feature on most sites and are typically witty or involve clever wordplay. They are synonymous with catchphrases, tag-lines, mottoes, and so on.

Drupal offers a global setting to store the site slogan which is customarily displayed by themes near the site logo or site name, and is also regularly added to news feeds and site e-mails as part of the site's identity.

Getting ready

Think up a good slogan! This is the biggest stumbling block to getting this recipe right.

How to do it...

Adding a slogan to a theme involves the following steps:

  1. Navigate to admin/settings/site-information (Home | Administer | Site configuration | Site information).

  2. Locate the Slogan textfield and add the slogan here as shown in the following screenshot:

  3. Click on the Save configuration button at the bottom of the page to save our changes.

  4. Now, navigate to admin/build/themes (Home | Administer | Site building | Themes).

  5. Click on the Configure tab at the top of the page.

    The resulting page should have multiple tabs: one titled Global settings which affects all themes and others representing each enabled theme. Configuration options under the Global settings tab serve as the site's default settings for all themes while equivalent settings within each theme's tab work as overrides for the global settings.

  6. On the Global settings page, look for the Site slogan setting in the Toggle display section and ensure that it is checked.

  7. Click on the Save configuration button to save our changes.

Tip

If any of the themes have overridden the global settings, then the Site slogan checkbox will also need to be checked in its respective theme tab.

How it works...

Drupal saves the provided slogan as a configuration setting in the database. The theme system makes this setting available as a variable to the theme which outputs it accordingly when the page is being rendered.

In the following screenshot, we can see that the slogan is enabled and is displayed below the logo and name of the site.

There's more...

Besides the site slogan, other site variables are also available on the theme configuration pages.

Similar settings

The Drupal Site information page seen in this recipe also contains fields for other settings such as the site name, mission, and footer which are also similarly exposed by themes.

 

Allowing users to choose from multiple themes


This recipe details the steps involved in enabling users to choose which theme they wish to use when they are viewing the site. For example, users with accessibility issues might prefer to view the site using a high-contrast theme, or those viewing the site via monitors with low resolutions might prefer a theme which uses a fluid layout.

Drupal's flexible approach to themes includes the ability to allow theme-specific block arrangements. As a result, this allows us to, for example, have a separate theme for site contributors with, perhaps, an extra sidebar equipped with a contributor-specific block arrangement.

Getting ready

Since we are going to be working with multiple themes in this recipe, we will need at least two themes to have been enabled on the site. This can be done via the theme administration page at admin/build/themes (Home | Administer | Site building | Themes) as seen earlier in this chapter.

How to do it...

We can enable users to choose between the different themes which are available through the following steps:

  1. Navigate to admin/user/permissions (Home | Administer | Users | Permissions).

  2. Scroll down to the section titled system module dealing with system-level permissions.

  3. Check the box labeled Select different theme for the authenticated user role.

  4. Click on the Save permissions button to save our changes.

  5. Now, visit the My account page at the path user and click on the Edit tab at the top.

  6. Locate the newly available section titled Theme configuration.

  7. Choose the preferred theme by selecting the associated radio button as in the following screenshot:

  8. Click on the Save button at the bottom of the page to register our changes.

How it works...

Drupal saves the users' choice as a configuration setting in the database. When a page is to be displayed, Drupal notices this setting and themes the page using the specified theme instead of the site's default theme.

 

Displaying a different theme for administration


This recipe describes how to set up Drupal to use a different theme only for administration pages. This is a frequent requirement especially on brochure sites which have a limited number of regions where blocks can be placed, or have missing page elements such as breadcrumbs which reduces usability. Having a separate administration theme also comes in handy during custom theme design as the site could well be largely unusable during the initial stages of development. A stable administration interface will therefore ensure that administrative tasks can still be performed effortlessly until the new theme becomes ready.

Getting ready

Depending on the amount of real estate required, it will be worthwhile to put some thought into deciding on the right theme to use as the administration theme. Themes such as the aptly named Administration theme (http://drupal.org/project/admin_theme) and RootCandy (http://drupal.org/project/rootcandy) have been designed specifically with the administration pages in mind. That said, if the requirement is temporary, using a core theme such as Garland will usually suffice.

How to do it...

Specifying an administration theme can be done by following these steps:

  1. Navigate to admin/settings/admin (Home | Administer | Site configuration | Administration theme).

  2. Choose Garland (or any other theme of choice) in the Administration theme drop-down list.

    In situations where only administrators have permissions to add and edit content, it might be handy to also check the Use administration theme for content editing checkbox seen in the previous screenshot.

  3. Click on the Save configuration button to save our changes in the database.

Viewing an administration page should confirm that the specified administration theme is being used in preference to the default theme.

How it works...

Every time a page is displayed, Drupal checks to see if the URL of the page begins with admin. If it does, and if we have specified an administration theme, Drupal overrides the default theme being used with the specified theme.

Tip

Since the administration theme is something of a special case, Drupal does not require the theme to be enabled for it to be available as an option.

 

Adding an existing block to the theme


Drupal's page layout is customarily divided into a content area and a number of regions which are laid out differently from theme to theme. For example, a theme could have a region named Left sidebar and Right sidebar which will be displayed to the left and right-hand side of the content respectively. Regions serve as containers for blocks.

Blocks are self-contained elements which are located within regions and typically contain information or functionality which is repeated consistently across multiple pages. They can contain contextual information which complements the actual content of a page, such as a block which outputs information about the author of the node currently being displayed, or static information, such as a login form block or a block which displays advertisements.

This recipe details the steps involved in adding an existing block to a region of a theme.

Getting ready

For this example, we will be adding a Who's online block to the left sidebar region (assuming that the theme has declared such a region). The position of a block both in terms of region as well as its weight (which determines its order among other blocks in the same region) can prove to be very important in terms of usability and exposure.

How to do it...

The Who's online block can be added by following these steps:

  1. Navigate to admin/build/block (Home | Administer | Site building | Blocks).

  2. If more than one theme is enabled on the site, choose the appropriate tab at the top of the page.

  3. Look for the Who's online block under the Disabled section.

  4. Click on the cross-hairs icon to its left and drag the block to the Left sidebar region.

    Alternatively, we could have simply chosen the Left sidebar in the Region dropdown and then used the cross-hairs to order the block within the region. This is the quicker option when there are a lot of blocks and regions to deal with on this page.

  5. Click on the Save blocks button at the bottom of the page to save our changes.

The block should now be visible in the left sidebar as can be seen with the Garland theme as follows:

How it works...

Drupal maintains a table named blocks in its database which contains a list of all the blocks exposed by the modules in its installation. By moving the Who's online block to the Left sidebar region, we are effectively just manipulating this table in the database. When a page is displayed, Drupal uses this table to determine the status and location of each block for the current theme and the theme system positions them accordingly.

There's more...

Block layouts are particular to each theme and can therefore be customized accordingly.

Theme-specific block layouts

Seeing as to how each theme is laid out differently with its own set of regions, it stands to reason that a block can also be positioned in different regions for different themes. For example, the Who's online block seen in this recipe can be positioned in the Left sidebar region of the Garland theme and the Right sidebar of another theme such as Bluemarine. Taking this idea further, we can also have the block enabled only for Garland and not for Bluemarine.

The block layout for each theme can be managed by clicking on the appropriate theme tab at the top of the block management page at admin/build/block (Home | Administer | Site building | Blocks). The page will be rendered using the theme being configured, thereby providing a preview of the theme and its regions.

 

Adding a custom block to the theme


This recipe details the steps involved in adding a block with custom content to the theme. Drupal blocks can either be declared using a module or, as we are doing here, added manually via the block administration interface.

Getting ready

For this recipe, we will be adding a simple welcome message in a custom block within a predetermined region. As with standard blocks, position matters!

How to do it...

The following procedure outlines the steps required to add a custom block to a theme:

  1. Navigate to admin/build/block (Home | Administer | Site building | Blocks).

  2. Click on the Add block tab at the top of the page.

  3. In the Block specific settings fieldset, type Welcome message in the Block description text field.

    This description field comes in handy on the Block administration page when trying to differentiate between blocks with identical titles, or as is frequently the case, no titles.

  4. Next, if the block requires a title to be displayed above its content, add one via the Block title textfield. In this case, we do not need one as we are just looking to display a welcome message.

  5. Enter the following text into the Block body textarea: Welcome to Mysite. Enjoy your stay!.

    Similar to most other textareas in Drupal, a linked Input format should be available to filter the content appropriately.

  6. Finally, click on Save block to create the block.

How it works...

Just as with standard blocks, Drupal maintains a table named boxes which tracks all custom blocks including their content and input format. Once a custom block is enabled, it is added to the blocks table and tracked as if it was a standard block.

When created, a custom block appears in the block list and can be treated just like any other block. It can be dragged around different regions, have its visibility settings controlled, and so on. The following screenshot displays our newly created welcome block:

Tip

An easy way to identify custom blocks on the block management page is by their telltale delete links. Only custom blocks feature a delete option.

There's more...

Custom blocks are useful in rendering more than just simple text strings.

Doing more with custom blocks

Custom blocks can be very handy to not only add visible content, but also to execute short code snippets on specific pages, provided the appropriate input format has been selected. For example, we could embed some custom JavaScript required only for a few specific page nodes, by adding it to a custom block—equipped with a suitable input format—which is set to be displayed only with the aforementioned page nodes.

That said, if a more optimal solution is available—such as using a module to hold our code—then it should be pursued instead of inserting code into blocks and thereby into the database.

 

Displaying a block only on the front page


This recipe details the steps involved in displaying a block only on a certain page, which in this case, is the front page. We will be displaying the welcome message block created in the previous recipe as an example.

Getting ready

The front page is a special case on most sites as it usually showcases the rest of the site. Manipulating block visibility for front page blocks is a frequent requirement and, in our case, we are going to ensure that the welcome message block is only going to be displayed on the front page and nowhere else.

How to do it...

Block visibility is controlled from the block's configuration page as follows:

  1. Navigate to admin/build/block (Home | Administer | Site building | Blocks).

  2. Locate the block which needs to be configured—the Welcome message block—and click on the Configure link next to it.

  3. On the configuration page, scroll down to the Page specific visibility settings section and select the Show on only the listed pages radio button.

  4. Further down in the textarea titled Pages, add the word <front>.

  5. Click on the Save block button at the bottom of the page to save the changes.

How it works...

Whenever a block is to be displayed, Drupal checks to see if we have any visibility settings applied to it. In this case, we have Show on only the listed pages switched on. As a result, Drupal checks the Pages textarea to see which pages have been listed. The use of the <front> keyword, which is a special indicator that represents the front page of the site, tells Drupal that unless this is the root of the site, this block should not be displayed.

This is all done before the content of the block is processed by Drupal thereby improving performance and making this method cleaner and more efficient than hiding the block using CSS or elsewhere in the theme.

There's more...

Drupal offers a number of page-matching options to further help refine when and where we display our blocks.

Multiple pages

Multiple pages can be specified in the Pages textarea. For example, if the block is to be displayed on the front page and on user pages only, the list would be the following:

<front>
user/*

Drupal will now compare the path of the page against each entry in this list and decide to display the block only if there is a match.

Tip

Wildcards

The use of the asterisk wildcard in user/* states that the match should be performed against all paths beginning with user. This ensures that the block is displayed for all pages within every user's My account section.

Matching against URL aliases

Drupal's Path module allows users to specify aliases for nodes and system paths. While this might lead to the conundrum of which paths to use while specifying a block's page-visibility settings, the Block module's page-matching code intelligently compares against both possibilities. For example, consider the following table which specifies the internal paths and corresponding aliases for three nodes:

Internal path

URL alias

node/1

products/foo

node/13

products/bar

node/22

products/baz

If we wanted to match against all three nodes, we could specify the three node paths directly:

  • node/1

  • node/13

  • node/22

Or, we could specify the three aliases as follows:

  • products/foo

  • products/bar

  • products/baz

Alternatively, we could simply use the aliases with a wildcard:

  • products/*

Exclusive display

This recipe can also be similarly applied to display a block on all pages but the front page. This involves choosing the Show on every page except the listed pages option in the Page specific visibility settings section.

 

Controlling block visibility based on user role


This recipe details the steps involved in toggling block visibility based on which type of user is viewing the page. For example, a block displaying advertisements might only need to be visible for anonymous users and not for authenticated users.

Getting ready

For this recipe, we will be configuring the welcome message block which we created in an earlier recipe in this chapter, to only be visible to authenticated users.

How to do it...

Controlling block visibility is handled from the block administration pages as outlined in the following:

  1. Navigate to admin/build/block (Home | Administer | Site building | Blocks).

  2. Locate the block which needs to be configured—the Welcome message block—and click on the Configure link next to it.

  3. On the configure screen, scroll down to Role specific visibility settings.

  4. Check the box corresponding to the authenticated user role which should have access to the block.

  5. Click on the Save block button at the bottom of the page to save the changes.

How it works...

Drupal maintains a table named block_roles which keeps track of role-specific settings for all blocks. Changes made to role settings on the block configuration page are stored in this table. When an anonymous user now visits the site, Drupal will not display the Welcome message block.

 

Controlling block visibility based on node type


Thus far in this chapter, we have looked at controlling block visibility based on the path of the page and the role of the user. In this recipe, we will look to configure a block to be displayed based on the node type of the content on the page.

Getting ready

We will be configuring the Recent comments block—which is provided by the Comment module—to only be visible for the story and blog node types. While the story type is enabled by default, the blog type is created only upon enabling the Blog module from the module administration page at admin/build/modules (Home | Administer | Site building | Modules).

It is assumed that both the Blog and Comment modules have been enabled, and sample nodes and associated comments have been created.

How to do it...

Block visibility can be configured from the block's configuration page as per the following steps:

  1. Navigate to admin/build/block (Home | Administer | Site building | Blocks).

  2. Look for the block which needs to be configured—Recent Comments—and click on the Configure link next to it.

  3. Navigate down to the Page specific visibility settings section.

  4. Select Show if the following PHP code returns TRUE and enter the following code in the Pages textarea below:

    <?php
    // Array of allowed types.
    $types = array('blog', 'story');
    // Check if the current page is a node.
    if ((arg(0) == 'node') && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    return in_array($node->type, $types);
    }
    ?>
    
  5. Click on the Save block button to save the changes.

  6. Back on the block administration page, ensure that the block has been enabled and added to one of the current theme's available regions such as the left or right sidebar.

How it works...

Since we have chosen to control block visibility using PHP, Drupal evaluates the code within the Pages text area and only displays the block if it returns the value TRUE.

The variable $types contains the list of allowed node types. This list is populated with the internal names of each node type which can be accessed via the Content types page at admin/content/types (Home | Administer | Content | Content types).

In the previous screenshot, the internal names of each type are listed under the column titled Type.

Since blocks are not restricted to only be visible on node pages, we need to ascertain if the page that is currently being viewed is a node page. We do this by checking the path to see if it matches the pattern node/node-id. In other words, we only consider displaying the block if the path involves the word node followed by the node ID, an integer.

Once we have ensured that we are viewing a node, we need to get Drupal to load the node using the node_load() function so that we can check if its type matches one of the types that we have allowed.

If the type of the node being viewed is in this list of allowed types, then the in_array() call returns TRUE and the block is displayed. Else, it returns FALSE which leads to the block not being displayed.

Tip

Good practice

Always add comments to code. If the code snippet has been taken from a website or a book, add a comment mentioning the URL or page number for future reference.

About the Authors
  • Karthik Kumar

    Karthik Kumar is a Drupal developer residing in Chennai, India. He first came across Drupal in late 2004 and has been a fan ever since. He maintains a number of modules on http://drupal.org under the moniker Zen – http://drupal.org/user/21209.

    Browse publications by this author
  • Dries Buytaert

    Dries Buytaert is the founder of Drupal and Acquia. He's been working on Open Source and on Open Web for 20+ years. He's also a blogger, photographer, traveler, investor, husband, and father of two wonderful kids.

    Browse publications by this author
Drupal 6 Theming Cookbook
Unlock this book and the full library FREE for 7 days
Start now