Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Drupal 6 Theming Cookbook
Drupal 6 Theming Cookbook

Drupal 6 Theming Cookbook: Over 100 clear step-by-step recipes to create powerful, great-looking Drupal themes

eBook
Mex$722.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Drupal 6 Theming Cookbook

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.

Left arrow icon Right arrow icon

Key benefits

  • Take control of the look and feel of your Drupal website
  • Tips and tricks to get the most out of Drupal's theming system
  • Learn how to customize existing themes and create unique themes from scratch
  • Part of Packt's Cookbook series: Each recipe is a carefully organized sequence of instructions to complete the task as efficiently as possible

Description

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.

Who is this book for?

This book is written for Drupal developers who want to refresh the look and feel of their sites. If you are a Drupal site administrator who is looking to go beyond the basics and customize the presentational aspects of your Drupal site, then this book is for you. It assumes that readers are familiar with rudimentary PHP and acquainted with Drupal installation and general usage. Readers are also expected to have knowledge of CSS and XHTML.

What you will learn

  • Beef up your knowledge of the basics of Drupal theming such as installing and enabling a downloaded theme, changing the logo, and adding a slogan to the theme
  • Customize the look of your website by configuring and extending your existing themes with sub-themes
  • Create custom themes from scratch for websites that demand a fresh look
  • Use the PHPTemplate theming engine to override module output and style it using a theme
  • Style and manipulate the content of your website by adding CSS and JavaScript files via themes and modules
  • Use the ImageCache module to manipulate images on the fly
  • Jazz up the design of your site by incorporating JavaScript elements
  • Make your Drupal site stand out from the crowd by customizing Views via the theme layer
  • Design complex site layouts rapidly with Panels
  • Speed-up development and debugging with Drupal tools such as the Devel module
  • Customize your Drupal site in a creative style by making thorough use of Drupal s APIs

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 12, 2010
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781847198693
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Nov 12, 2010
Length: 384 pages
Edition : 1st
Language : English
ISBN-13 : 9781847198693
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 3,138.97
OpenVPN 2 Cookbook
Mex$1128.99
Drupal 7 Social Networking
Mex$1004.99
Drupal 6 Theming Cookbook
Mex$1004.99
Total Mex$ 3,138.97 Stars icon

Table of Contents

12 Chapters
Drupal Theme Basics Chevron down icon Chevron up icon
Beyond the Basics Chevron down icon Chevron up icon
Custom Themes and Zen Chevron down icon Chevron up icon
Templating Basics Chevron down icon Chevron up icon
Development and Debugging Tools Chevron down icon Chevron up icon
Advanced Templating Chevron down icon Chevron up icon
JavaScript in Themes Chevron down icon Chevron up icon
Navigation Chevron down icon Chevron up icon
Form Design Chevron down icon Chevron up icon
Customizing CCK Chevron down icon Chevron up icon
Views Theming Chevron down icon Chevron up icon
Rapid Layouts with Panels Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
(2 Ratings)
5 star 0%
4 star 100%
3 star 0%
2 star 0%
1 star 0%
Paul Crisp Mar 22, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I've tried quite a lot of Drupal manuals and this is definitely the best I've found. Theming is a bit of a dark art with multiple interacting components. The Cookbook covers a lot of territory but does so very clearly. It also manages to show exactly how to accomplish something AND explain what your doing and how it works. Probably not geeky enough for a Drupal Master and does require a bit basic knowledge about php and CSS but a good allrounder could cope fine with this. Recommended
Amazon Verified review Amazon
Geoffrey G. Hankerson Feb 10, 2011
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
In Drupal or any Web development environment, the themer's job is to make the site look nice. This might mean making a Photoshop mockup into a real site, or implementing a design in another way. A themer is expected to use CSS, JavaScript and some Php to make this happen.This cookbook offers recipes to help the themer do his job. The recipes start simple with tips on how to download a contributed theme from Drupal.org and install it. The recipes then quickly move to show you how to make a custom theme from scratch or using Zen as a base theme. One recipe walks you through the components of a theme step by step so you can get started on your own theme. The recipes build from there.Some of the other basic recipes I like include: customizing a node template for a specific node type, including a CSS of javascript file in a theme, and optimizing CSS and Javascript for production sites.I also really appreciated the fact that the author encourages the use of a custom module for theme customizations. A lot of themers get caught up in working their theme's directory only and never realize the advantage of using a module to add javascript to a specific page, change a form submit button into an image, etc... (The advantage is the code is more easily reused on another site).What I especially like about the book is the fact that there are several good recipes for experieced themer's like me in addition to basic recipes. Some of the more advanced tips I looked included using Firebug's console.trace for JavaScript debugging, making Php variables available to JavaScript, and even a simple example of a Views Style plugin. I've been wanting to learn to make views style plugins to expose some of those cool jquery effects out there in the wild. This gives me great starting point.The one thing I wish the book would emphasize more is most of implementing a theme still is writing CSS. Often the point of a fancy theme preprocess function is to add a CSS ID or class to some part of the markup so we can target it properly with CSS. This is however a small gripe.This cookbook along with "Front End Drupal" are an essential part of any Pro Themer's library.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.