Archive for the ‘Drupal’ Category

HOW TO INSTALL & SETUP VIEWS SLIDESHOW MODULE ON DRUPAL7?

Thursday, April 7th, 2011

(1) Required Modules (Version: Drupal7.0)

  1. Views
  2. Views Slideshow
  3. Chaos tool suite
  4. Link Field
  5. Token (optional)

(2) Install the Modules

In Drupal7 you can install modules from the admin section, but I still feel this new feature doesn’t have any meaning, because we have to search for the module link in the Druapl site and then copy paste into the admin module installation area, really crazy. It would have been so good if they would have made it something like wordpress a small search feasture. Anyway I just gonna download and istall it in the old way (I still recommend this old way).

Download all the modules from Drupal site and install in the directory yoursitename/sites/all/modules.
Go to http://www.yoursitename.com/node#overlay=admin/modules and enable these modules as below;

(1) Views (2) Views UI (3) Views Slideshow (4) (5) Chaos tools (6) Link

(3) Create Image Cache

In Drupal7 imagecache is part of core module and is named as Image styles. So let’s create two image cache from here, one for the full size slider image and other for the thumbnail image. In this tutorial I use 935×293 (pixels) dimension for the full size slider image and 210×100 (pixels) dimension for the thumbnail image. Note: These configurations csn be defered depends on your needs.

* Fullsize Slider image settings

Go to http://www.yoursitename.com/node#overlay=admin/config/media/image-styles and click on the add new style link
(1) Give an Image style name and click on create new style button
(2) On the next configuration screen select new style you want and then click add button (In this tutorial I choose resize style)
(3) On the next screen set the width and height and click on the add effect button. (The settings may vary depend on the style you choose). I set width as 935 and height as 293 pixels.

Do this same process for the thumbnail image too. (for the thumbnail image dimension, I set width as 210 and height as 100 pixels.)

(4) Create New Content Type

Let’s create a new content type, From the dashboard menu bar cick on Structure and then content types then click on the add new content type link.

(1) Give a human-readable name, I named it as Featured Slider (machiine name will be auto generated based on the human readable name)
(2) Give a brief and relevant description
(3) Submission form settings, I leave as the default settings
(4) Publishing options, I checked only published (all other settings unchecked)
(5) Display settings, I have unchecked the authour and date info.
(6) Comment settings,I set hidden (disabled)
(7) Menu settings, I leave as default settings.
(8) Click Save and add fields Button

(5) Create New Fields

Here in this example I create only two fileds, and they are image field and link field.
We will use image field for uploading our slider image and link field for creating a custom link where we want our slider to be linked.

Image Field Settings

(1) Label: Slider Image
(2) Field: slider_image
(3) Field type: image
(4) Widget (form element): image
(5) Click Save button, and on the field settings page leave default settings and click on Save field settings button.
(6) On the image field configuration settings page you can configure as you wish.
I set this field as required, I added a file director name called slider-image so that this images will be arranged sperately from other images.
You can set the maximum upload size and resolution here, I have anabled alt and title field and finally click Save settings button.

By using same method create the link field too.

Link Field Settings

(1) Label: Slider Link
(2) Field: slider_link
(3) Field type: link
(4) Widget (form element): link
(5) Click Save button,
For the link field configurations leave evrything to default settings.
I have re arranged the field like shown below;
Title field
Image field
Link field
Body field (you can even remove this field if not necessary)
Manage Display
On the manage display tab you can conigure how the out put of the field to be diplayed.
I have set the link field as hidden and I have also set image label as hidden
Drupal7: manage fields

(6) Create Feature Slider Content

I have created four featured slider content for this tutorial.

(1) Click on add content link
(2) Create Featured Slider content
(3) Give a proper title name
(4) Upload slider image
(5) Give alt and title field names
(6) Give a link title and url where you want the slider to be linked
(7) Leave all othe settings as default except for the path field if yo want you can give an SEO friendly URL alias.
(8) Save the content.

Same way create more Featured Slider contents (I have created four contents)

(7) Create a New View

Now it’s time to create our new Slideshow view.
From the Dashboard menu click on the Structure and then click on the Views.

(1) Click add new view link
(2) Give view name, I have named as Featured Slider (machiine name will be auto generated)
(3) Give an apropriate view description
(4) Choose view type as node and click Next button.
Views Field Settings
First let’s add link field (link must be the first field in order to work everything properly) so click on the + icon and from the Groups select Fields
Add link field (field_slder_link), remove the label and leave all other settings as default and click Update button.

Next let’s add image field, so click on the + icon and from the Groups select Fields
Add image field (field_slider_image) make sure you choose the image field which we crerated for this slider only.
Remove the label and in the Rewriting section click Output this field as a link and then you get more configuration options just do as given below;

(1) Scroll dow a bit and you can see replacement patterns created by Core Token module, (if we didn’t set the link field as first we can’t see link field option here) copy only [entity_id] then scroll up and paste it in the link path field.
(2) Scroll down to te bottom of the settings and choose Image Style as fullsize-image (Our fullsize image style we created above).
Leave all other settings as default. Click Update button.

Finally we need one more field for the thumbnail, so let’s click on the + icon and from the Groups select Fields
Add image field (field_slider_image) make sure you choose the image field which we crerated for this slider only.
Remove the label and CHECK EXCLUDE THIS FIELD FROM DISPLAY, then in the Rewriting section click Output this field as a link and then you get more configuration options just do as given below;

(1) Scroll dow a bit and you can see replacement patterns created by Core Token module, (if we didn’t set the link field as first we can’t see link field option here) copy only [entity_id] then scroll up and paste it in the link path field.
(2) Scroll down to te bottom of the settings and choose Image Style as slider_thumb (Our thumbsize image style we created above).
Leave all other settings as default. Click Update button.

Views Filters Settings

Now let’s create a filter for filtering to get the specific content.
(1) So let’s click on the + icon and from the Groups select Node
(2) Select Node Type as Featured Slder
(3) Select Node Published as Yes

Views Style Settings

Click on the Unformatted link under style settigs and choose Slideshow and on the next configuratioin window set as below;
(1) List type: Unordered list
(2) Wrapper class: Leave default settings
(3) Style> Skin: deafult
(4) Slides> Slideshow type: cycle
(5) Cycle options
You need to download jQuery cycle plugin and copy jquery.cycle.all.min.js to sites/all/libraries/jquery.cycle You can find the plugin at http://malsup.com/jquery/cycle.
(6) Transittion: Fade
(7) Action: pause on hover
(8) Internet Explorer Tweaks: default
(9) Widgets: You can choose either or both Top and Bottom (I choose bottom here, and the advance settings as below;)
(10) Bottom Widgets>Pager>Pager type: Fields
(11) Pager field: field_slider_image (last one we added for the thumb, don’t mistake since both field will be named same.)
(12) Activate Slide and Pause on Pager Hove: checked, controls and slider counter leave unchecked.
(13) Click Update button.

Row Style Settings

  1. Row Styel: Fields Selected, then on the rowstyle settings section you see an option with display inline.
    Choose the thumbnail field as inline.
  2. Click Update button. (Note: Well it actually doesn’t change much in appearance bit it does change in the code. Next step use the firebug and find the class and add some styles to display properly.)

Add New Display

On the views left side choose block and click on Add display button. And re-name the block as Featured Slider under views Basic Settings.

Drupal7: fviews slideshow Slider

(8) Create a Custom Region (optional step)

(1) On your thems folder open the your_theme_name.info file and add a new region like this shown below;
regions[featured_slider] = Featured Slider and save the .info file.
(2) Open your themes page.tpl.php file and add these code where you want your slide to be displayed as shown below;

<?php if ($page['featured_slider']): ?>
<div id=”featured-slider”>
<?php print render($page['featured_slider']); ?>
</div> <!– End Featured Slider–>
<?php endif; ?>

You can even create custom front page template like page–front.tpl.php so that you do’t need to make any changes to the default page.tpl.php template.

[9] Enable & configure the Block

Now this block will be visible in the blocks disabled area, so from the Dashboard menu go to Structure>Block and enable the block to a themes default region  or the custom region we created (featured_slider). (Regions varies depends on the theme you are using.)

Block Configuration Settings
After enabling the block you get a link to configure the block so click on the Configure link and on the settings section set as below;

(1) Block title (if you don’t want blobk title to be displayed just type <none>)
(2) Again you get all enabled theme specific Region settings.
On visibility setings
(3) Pages>Show block on specific page: choose Only the listed pages and type <front> so that this block will be displayed only on the front page.

That’s all now we have successfully created our new Views Slideshow on Drupal7. I hope yo could understand the tutorial I tried my best to explain as much as I can, if you still have doubt’s comment below and I will try my best to help. The scren cast of this tutorial will be coming soon.

Play around and find the best you can in Drupal7, Best wishes.

Converting 6.x themes to 7.x

Monday, April 4th, 2011

Overview of Drupal Theme changes in 7.x

  1. [UBlocks have new, more meaningful CSS IDs
  2. [UPrimary and secondary links are now Main and Secondary menu
  3. [UUnrendered taxonomy links are no longer available as a separate variable in node.tpl.php files
  4. [URDFa requires some changes at the beginning of html.tpl.php
  5. [UThe clear-block class has been renamed to clearfix
  6. [UThe box.tpl.php template has been removed
  7. $help became a region
  8. [UMission statement removed, ‘highlighted’ region suggested
  9. [UFooter message removed
  10. [UContent region is now mandatory, main page content became a block
  11. [USecond phase variable process functions
  12. HTML classes generated through a variable
  13. HTML attributes generated through a variable
  14. Variable process functions can now be used for all theming hooks
  15. All theme functions now take a single argument, $variables
  16. [UFunction names must match theme name
  17. [UAll CSS and JavaScript files must be specified in the theme’s .info file
  18. Renamed $block->content in block.tpl.php
  19. Granular rendering in node and user templates
  20. [UAdded jQuery UI (1.8) to core
  21. Attached JS/CSS for elements
  22. $closure becomes $page_bottom, new $page_top and hidden regions
  23. $left and $right variables are now $sidebar_first and $sidebar_second; CSS IDs also changed
  24. $picture changes to $user_picture, and the CSS class ‘picture’ to ‘user-picture’
  25. New classes available to hide content in an accessible manner
  26. JavaScript variable Drupal.jsEnabled has been removed
  27. PHPTemplate suggestion wildcard
  28. Include theme definition explicitly on element when using system_elements()
  29. Added markup to make installation task progress perceivable with screen-reader and CSS disabled.
  30. Added an invisible heading to theme_breadcrumb().
  31. Changes to alt and title attribute for the RSS feed icon
  32. Search box moved from theme layer to blocks
  33. Changes to menu tree, link and tab rendering functions
  34. theme_links() has a new parameter $heading for accessibility
  35. theme_get_setting() and THEME_settings() have been improved
  36. Added a theme_form_required_marker() function
  37. Added a theme_link() function
  38. Skip to main content links in core themes
  39. Alter hooks available to themes
  40. System module stylesheets have been reorganized to separate behavior-supporting styles from presentational styles
  41. New theme setting for displaying the Shortcut module “add to shortcuts” link
  42. Specific template overrides of generic templates use a ‘–’ delimiter instead of ‘-’
  43. CSS files are sometimes loaded with @import, sometimes with LINK tags
  44. [UBrowser-targeted CSS files can and should be added using drupal_add_css()
  45. Targeted overrides (suggestions) available for theme_menu_link() and theme_menu_tree()
  46. theme_submenu() was removed
  47. New $title_prefix and $title_suffix template variables
  48. theme_node_form() was removed
  49. node_get_types() renamed to node_type_get_types()
  50. Core themes now contain “package = Core” in their .info files
  51. Heading elements added to search-result.tpl.php
  52. The name attribute in a and map elements is invalid
  53. PHPTemplate is now the default theme engine

Blocks have new, more meaningful CSS IDs

Many of the CSS IDs for blocks defined by Drupal core have changed so that they more clearly indicate the purpose of the block:

Recent blog posts
Old CSS ID (Drupal 6): block-blog-0
New CSS ID (Drupal 7): block-blog-recent

Book navigation
Old CSS ID (Drupal 6): block-book-0
New CSS ID (Drupal 7): block-book-navigation

Recent comments
Old CSS ID (Drupal 6): block-comment-0
New CSS ID (Drupal 7): block-comment-recent

Active forum topics
Old CSS ID (Drupal 6): block-forum-0
New CSS ID (Drupal 7): block-forum-active

New forum topics
Old CSS ID (Drupal 6): block-forum-1
New CSS ID (Drupal 7): block-forum-new

Language switcher
Old CSS ID (Drupal 6): block-locale-0
New CSS ID (Drupal 7): block-locale-language-switcher

Syndicate
Old CSS ID (Drupal 6): block-node-0
New CSS ID (Drupal 7): block-node-syndicate

Most recent poll
Old CSS ID (Drupal 6): block-poll-0
New CSS ID (Drupal 7): block-poll-recent

Author information
Old CSS ID (Drupal 6): block-profile-0
New CSS ID (Drupal 7): block-profile-author-information

Search form
Old CSS ID (Drupal 6): block-search-0
New CSS ID (Drupal 7): block-search-form

Popular content
Old CSS ID (Drupal 6): block-statistics-0
New CSS ID (Drupal 7): block-statistics-popular

Powered by Drupal
Old CSS ID (Drupal 6): block-system-0
New CSS ID (Drupal 7): block-system-powered-by

User login
Old CSS ID (Drupal 6): block-user-0
New CSS ID (Drupal 7): block-user-login

Navigation
Old CSS ID (Drupal 6): block-user-1
New CSS ID (Drupal 7): block-system-navigation

Who’s new
Old CSS ID (Drupal 6): block-user-2
New CSS ID (Drupal 7): block-user-new

Who’s online
Old CSS ID (Drupal 6): block-user-3
New CSS ID (Drupal 7): block-user-online

For example, a Drupal 6 CSS style declaration such as:

/* Make the text in the user login block bigger. */
#block-user-0 {
font-size: 1.5em;
}

should become (in Drupal 7):

/* Make the text in the user login block bigger. */
#block-user-login {
font-size: 1.5em;
}

[Docs Updated]

Primary and Secondary links have been renamed to Main and Secondary menu. Themes which support these options will need to be updated to use the new variable names:

6.x: page.tpl.php

<div id="menu">
<?php if (isset($secondary_links)) { ?><?php print theme('links', $secondary_links, array('class' => 'links', 'id' => 'subnavlist')); ?><?php } ?>
<?php if (isset($primary_links)) { ?><?php print theme('links', $primary_links, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?>
</div>

7.x: page.tpl.php

<div id="menu">
<?php if (isset($secondary_menu)) { ?><?php print theme('links', $secondary_menu, array('class' => 'links', 'id' => 'subnavlist')); ?><?php } ?>
<?php if (isset($main_menu)) { ?><?php print theme('links', $main_menu, array('class' => 'links', 'id' => 'navlist')) ?><?php } ?>
</div>

You will also need to make the appropriate variable name changes if your theme’s theme.info is defining features[]. Defining renamed or replaced features may cause all features to render as blank or empty arrays.

6.x: theme.info – features[]

features[] = primary_links
features[] = secondary_links

7.x: theme.info – features[]

features[] = main_menu
features[] = secondary_menu

Also, if your theme.info is defining features[] = mission please note that this feature has been removed and replaced with a variable named $mission which can be output in your page template.

[Docs Updated]

Unrendered taxonomy links are no longer available as a separate variable in node.tpl.php files

Previously, node.tpl.php files could use the $taxonomy variable if they needed access to an array of unrendered taxonomy links associated with the current node.

In Drupal 7, this is no longer the case. Instead, all links have been moved into the $nodeobject. The array of unrendered taxonomy links can now be found in $node->content['links']['terms']['#value'] instead. (Note that this array should be used with caution, since the text contained within it has not been escaped to prevent XSS attacks.)

Rendered taxonomy links are not affected; node.tpl.php files can continue to access these via the $terms variable, as before. In many cases, the $terms variable is what you want to use in your theme anyway, and you might be able to replace references to $taxonomy with it, as in the following example:

6.x

<?php if ($taxonomy): ?>
<div><?php print $terms ?></div>
<?php endif;?>

7.x

<?php if ($terms): ?>
<div><?php print $terms ?></div>
<?php endif;?>

[Docs Updated]

RDFa requires some changes at the beginning of html.tpl.php

Drupal 7 is able to output RDFa which requires the following changes in html.tpl.php.

  • The DOCTYPE must be changed to XHTML+RDFa 1.0.
  • The old lang attribute should be removed for compatibility with XHTML 1.1, only xml:lang should remain.
  • The RDF namespace prefixes used throughout the HTML document need to be serialized in the html tag and are contained in the $rdf_namespaces variable.
  • The GRDDL profile should be specified in the <head> tag.

6.x

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">
<head>

7.x

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>"
<?php print $rdf_namespaces ?>>
<head profile="<?php print $grddl_profile ?>">

[Docs Updated]

The clear-block class has been renamed to clearfix

The “clear-block” class was a Drupalism for functionality that was better known by the CSS Community as the “clearfix” class. Also, using “block” in the old name was confusing to Drupal users more familiar with Drupal’s block system than with the properties inside that CSS ruleset. New themers and designers to the Drupal community will no longer be confused by the old class name.

If you had a <div> in your D6 theme, simply change it to <div>.

[Docs Updated]

The box.tpl.php template has been removed

The amorphous box.tpl.php template has been removed. Those pieces of content that were using the box.tpl.php now have their own theme functions.

The search results listings are just themed with theme(‘search_results’) instead of being wrapped in an additional box. The comment form box is themed with a theme_comment_form_box() theme function.

[Docs Updated]

$help became a region

(issue) In Drupal 7, a new region was added to the defaults (leftrightcontentheaderfooter) called help. By default, the textual content of this region is the same as the $helpvariable was in page.tpl.php for Drupal 6.

Themes in Drupal 7 need to ensure that the $help variable is printed in page.tpl.php and, if the theme overrode the default regions, that the following line is added to its .info file:

regions[help] = Help

The help text is now surrounded by the block.tpl.php template’s <div> tags and classes, so the CSS used to style the help likely needs changing.

[docs updated]

Mission statement removed, ‘highlighted’ region suggested

(issue) In Drupal 6, the page template received a special variable called $mission, which contained the mission statement setting of the website when on the front page. Drupal 6 themes also had an option on the theme settings page to toggle this functionality. Drupal 7 removes the mission setting and the option toggle in favor of the more general custom block placement in regions.

Drupal 7 core themes now include a region named ‘highlighted’ which uses the same display as the mission statement area in Drupal 6. Whether this region has content now depends on administrators setting block placement, and is not limited to the front page only. Content in the highlighted region will be surrounded by the block.tpl.php template’s <div> tags and classes, so the CSS used to style this area might need changing.

6.x

In .info:

features[] = mission

In page.tpl.php:

<?php print $mission; ?>

7.x

If you have defined custom regions in your .info file, you may add the highlighted region to the existing list of regions as shown below. If your theme does not define any regions, the highlighted region will be provided by core automatically, and you’ll only need to ensure that you print it in page.tpl.php.

in .info:

regions[highlighted] = Highlighted

in page.tpl.php:

<?php print render($page['highlighted']); ?>

[Docs Updated].

(issue) In Drupal 6, the page template received a special variable called $footer_message, which contained the footer message setting of the website. This was usually output before the footer region ($footer) by the template. Drupal 7 recognizes that the footer message was just a special type of user defined block. Those who had this setting in Drupal 6 will get a user defined block in the update, positioned in the $footer region.

To update your themes, just remove the $footer_message variable from them.

If you happened to output the $footer_message in your page template, but did not yet support the $footer region, now might be the time to start supporting this region. If you don’t override any regions, the footer region will be predefined for you. If you do override regions, please output the $footer content in your page template and include the footer region in your .info file:

regions[footer] = Footer

Support for the footer region is just suggested but not required by Drupal. Those upgrading from Drupal 6 with a theme lacking support for the footer region will be able to reposition their block to another region.

Content region is now mandatory, main page content became a block

In Drupal up to version 6, the $content variable in page.tpl.php contained the main page content appended with the blocks positioned into the content region (if you had that region defined).

In Drupal 7, $content became a full region and is now mandatory in all themes. This new requirement was set up so that when enabling new themes, Drupal knows where to put the main page content by default.

In Drupal 6, it was only possible to put blocks after the main page content in this region. The only way to put blocks before the main page content was to define a specific region for that purpose. Drupal 7 now makes the main page content its own block. This makes it possible to put blocks before or after the main page content in the region without hacking in a new region.

If you relied on the fact that blocks were only put in the sidebars and therefore got their styling via just a .block class selector or something similar, now you might need to revisit your CSS files. Because the main page content is wrapped by markup from block.tpl.php, the.block selector will match that too, so you need to limit your blocks styling to certain regions by making the selectors more specific, such as #left-sidebar .block.

Second phase variable process functions

There are now two sets of variables process functions. The first are the existing “preprocess” functions. The second are “process” functions which are run after preprocessors. All the various prefixes and suffixes apply to this second phase in the exact same way. This is useful when certain variables need to be worked on in two phases.

For example, adding classes into an array for the “preprocess” phase then flattening them into a string in the “process” phase so it’s ready to print within a template. See next section.

[Docs Updated].

HTML classes generated through a variable

All templates can now print out $classes from a template to render dynamic classes built from variable process functions. The way to add these dynamic classes is by feeding the variable key labeled “classes_array” like so:

<?php
function mytheme_preprocess_node(&$vars) {
// Add a striping class.
$vars['classes_array'][] = 'node-' . $vars['zebra'];
}
?>

The default “template_process” (second phase processor) will take care of flattening the array into a flat string making it ready to print from your template. Dynamic classes are generated for common templates by default but due to the way it’s set-up, any template can have a $classes variable.

Example:

<divborder-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; font-size: 12px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; vertical-align: baseline; color: rgb(0, 0, 0); background-position: initial initial; background-repeat: initial initial; "><?php print $classes ?>">
...
</div>

HTML attributes generated through a variable

All templates can now print out $attributes$title_attributes, and $content_attributesfrom a template to render dynamic attributes built from variable process functions. The RDF module and other modules add important information to these variables, so it is important for themes to ensure that these variables are printed correctly within all overridden template files. These three variables contain attributes for the overall element being rendered by the template, and its primary title and content elements, respectively. The way to add attributes to these variables is by feeding the variable keys labeled “attributes_array”, “title_attributes_array”, and “content_attributes_array” like so:

<?php
function mytheme_preprocess_node(&$vars) {
// If the node was saved with a log message and the currently logged in user
// has permission to view that message, add it as a title attribute (tooltip)
// when displaying the node.
if (!empty($vars['node']->log) && user_access('view revisions')) {
$vars['attributes_array']['title'] = $vars['node']->log;
}

// Force the direction of node titles to be left to right, regardless of
// language or any other settings.
$vars['title_attributes_array']['dir'] = 'ltr';
}
?>

The default “template_process” (second phase processor) takes care of flattening the arrays into strings ready to print within the template file. The flattening process results in either empty strings (if no dynamic attributes were set) or strings that have a leading space followed by attribute names and values. Because of this, the attributes variables should be printed directly next to what precedes it in the template, with no leading space.

Example:

<div id="..."<?php print $attributes; ?>>
<h2<?php print $title_attributes; ?>>...</h2>
<div<?php print $content_attributes; ?>>...</div>
</div>

As is shown in the example, the convention is for the “id” and “class” attributes to be printed explicitly within the template, and for the attributes variables to be used for all other attributes. Therefore, to ensure that no attribute gets printed twice within the same element, the following rules should be followed:

  • Preprocess functions within modules must not add “id” or “class” to the attributes arrays.
  • Preprocess functions within themes may add “id” and/or “class” to the attributes arrays, but if they do so, the theme must also override the corresponding template file and ensure that the same attribute isn’t being printed explicitly.
  • Templates must not print any attribute other than “id” or “class” explicitly on any element for which an attributes variable is also being printed. Instead, the theme must use a preprocess function, as shown above.

Variable process functions can now be used for all theming hooks

(issue) In Drupal 6, preprocess functions could only be used for theming hooks rendered by templates. In Drupal 7, hook-specific preprocess and process functions can be used for all theming hooks, whether rendered by templates or functions. For example, a theme can make all menu links that start with “http:” or “https:” (as opposed to ones that refer to an internal Drupal path) to open in a new browser tab:

<?php
function mytheme_preprocess_menu_link(&$variables) {
if (
substr($variables['element']['#href'], 0, 5) == 'http:' ||
substr($variables['element']['#href'], 0, 6) == 'https:'
) {
$variables['element']['#localized_options']['attributes']['target'] = '_blank';
}
}
?>

Every preprocess function adds to the time it takes to theme the item, so especially for theme functions that get called a lot, keep an eye on performance when adding preprocess functions.

To minimize performance overhead, the non-hook-specific preprocess and process functions are called for templates only. See the API documentation for theme() for the full list of hook-specific and non-hook-specific preprocess and process functions.

All theme functions now take a single argument, $variables

(issue) In Drupal 6, theme functions registered their function arguments in hook_theme(). In Drupal 7, all theme functions take a single argument, $variables, an array of keyed variables, and register the expected keys within this array in hook_theme().

6.x

<?php
function drupal_common_theme() {
return array(
...
'table' => array(
'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
),
...
);
}

function theme_table($header, $rows, $attributes = array(), $caption = NULL) {
...
}
?>

7.x

<?php
function drupal_common_theme() {
return array(
...
'table' => array(
'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE),
),
...
);
}

function theme_table($variables) {
$header = $variables['header'];
$rows = $variables['rows'];
$attributes = $variables['attributes'];
$caption = $variables['caption'];
$colgroups = $variables['colgroups'];
$sticky = $variables['sticky'];
...
}
?>

Function names must match theme name

Function names in the file template.php must now use the relevant theme’s name. You may no longer use phptemplate_function. This change was made in the following patch: Die, themeEngineName_ prefix, die!. To update your theme ensure there are no functions that begin with the template engine name (phptemplate) in the file template.php or any related template files.

All CSS and JavaScript files must be specified in the theme’s .info file

In Drupal 6 style.css and script.js would be included in your theme automatically, even if they weren’t present in the theme’s .info file. In Drupal 7, themes must specify these files in the .info file to include them. More information about this change can be seen at #351487: Remove default values for stylesheet and scripts includes from system module. If your theme doesn’t use these files, or if they are already specified in your theme’s info file, no changes are required. [docs updated]

Renamed $block->content to $content in block.tpl.php

See this issue for the whole story.

Granular rendering in node and user templates.

Issue. Template authors may now finally print out bits of node and profile content as they see fit and still maintain forward compatibility with new modules that might add new content. To do so, template authors should use 2 new functions – render() and hide(). Example taken from node.tpl.php:

<div>
<?php
// We hide the comments and links now so that we can render them later.
hide($content['comments']);
hide($content['links']);
print render($content);
?>
</div>

<?php print render($content['links']); ?>

<?php print render($content['comments']); ?>

render() returns all the items that are in $content. So, print render($content) is equivalent to the D6 print $content. When a templater wants to print out part of the $content array, she may do so with something like print render($content['links']). If the printing of links comes after the printing of all the rest of $content, then templater should call hide($content['links']) before calling print render($content). Then, the links can be printed further down in the template with print render($content['links']).

Added jQuery UI (1.8) to core

(issue) jQuery UI 1.8 was added to core. You can find the jQuery UI files in misc/ui and can add Javascript and CSS files from there to your pages with the regular drupal_add_js() and drupal_add_css() calls, no special function calls required. If you are migrating a theme which was previously dependent on the jquery_ui contributed module, see the module update guide on the topic, which provides examples. [docs updated]

Attached JavaScript and CSS for drupal_render

(issue) Individual elements now have the ability to define what JavaScript and cascading stylesheets are associated with them. This is stated in the #attached_js and #attached_cssproperty.

Drupal 6.x:

<?php
function example_admin_settings() {
// Add example.admin.css
drupal_add_css(drupal_get_path('module', 'example') .'/example.admin.css');
// Add some inline JavaScript
drupal_add_js('alert("You are visiting the example form.");', 'inline');
// Add a JavaScript setting.
drupal_add_js(array('mymodule' => 'example'), 'setting');
$form['example'] = array(
'#type' => 'fieldset',
'#title' => t('Example');
);
return $form;
}
?>

Drupal 7.x:

<?php
function example_admin_settings() {
$form['#attached_css'] = array(
// Add example.admin/css.
drupal_get_path('module', 'example') . '/example.admin.css'
),
$form['#attached_js'] = array(
// Add some inline JavaScript.
'alert("You are visiting the example form.");' => 'inline',
// Add a JavaScript setting. Note that when the key is a number, the 'data' property will be used.
array(
'data' => array('mymodule' => array(...)),
'type' => 'setting'
),
);
$form['example'] = array(
'#type' => 'fieldset',
'#title' => t('Example');
);
return $form;
}
?>

$closure becomes $page_bottom, new $page_top and hidden regions

(issue 1)(issue 2) Drupal 6 provides a special variable called $closure which should be put at the bottom of the HTML body output and can be themed via theme_footer() (which calls out to implementations of hook_footer() in modules). To generalize on one way to put output to the different page areas, Drupal 7 standardizes on regions and introduced the page_bottom region in place of the $closure special variable. Also, page_top is added as a pair of page_bottom. In Drupal 7 you need to output $page_top at the top of the HTML body output and $page_bottom at the bottom.

Drupal 6:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
...
<bodyborder-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; font-size: 12px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; vertical-align: baseline; color: rgb(0, 0, 0); background-position: initial initial; background-repeat: initial initial; "><?php print $body_classes; ?>">
...
<?php print $closure; ?>
</body>
</html>

Drupal 7:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN"
"http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
...
<bodyborder-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; font-size: 12px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; vertical-align: baseline; color: rgb(0, 0, 0); background-position: initial initial; background-repeat: initial initial; "><?php print $classes; ?>">
<?php print $page_top; ?>
...
<?php print $page_bottom; ?>
</body>
</html>

If you define custom regions, it is important to remember that you need to include the page_top and page_bottom regions in your set of regions.

theme .info file extract:

regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom

The page_top and page_bottom regions are hidden, which means they will not show up on the blocks administration interface. When doing site-specific themes, it might also be useful to add more hidden regions (to provide ways for modules to add output to more places in the theme without defining blocks showing up on the blocks interface), you can do that via the regions_hidden[] .info file array which is new to Drupal 7:

theme .info file extract:

regions[content] = Content
regions[help] = Help
regions[page_top] = Page top
regions[page_bottom] = Page bottom
regions[indicators] = Indicators
regions_hidden[] = indicators

(issue) In Drupal 6, the sidebar variable names were $left and $right. In Drupal 7 they are $sidebar_first and $sidebar_second.

6.x

<?php if (!empty($left)): ?>
<div id="sidebar-left">
<?php print $left; ?>
</div> <!-- /sidebar-left -->
<?php endif; ?>
...
<?php if (!empty($right)): ?>
<div id="sidebar-right">
<?php print $right; ?>
</div> <!-- /sidebar-right -->
<?php endif; ?>

7.x

<?php if ($sidebar_first): ?>
<div id="sidebar-first"><div>
<?php print $sidebar_first; ?>
</div></div> <!-- /.section, /#sidebar-first -->
<?php endif; ?>

<?php if ($sidebar_second): ?>
<div id="sidebar-second"><div>
<?php print $sidebar_second; ?>
</div></div> <!-- /.section, /#sidebar-second -->
<?php endif; ?>

This means that associated CSS IDs have changed as well:

Old CSS ID (Drupal 6) New CSS ID (Drupal 7)
#sidebar-left #sidebar-first
#sidebar-right #sidebar-second

[docs updated]

$picture changes to $user_picture, and the CSS class ‘picture’ to ‘user-picture’

The variable and the CSS class have been renamed to be more descriptive.

Drupal 6 (user-picture.tpl.php):

<div>
<?php print $picture; ?>
</div>

Drupal 7:

<?php if ($user_picture): ?>
<div>
<?php print $user_picture; ?>
</div>
<?php endif; ?>

New classes available to hide content in an accessible manner

Two new system classes have been added to be used for the purpose of hiding elements, .element-hidden and .element-invisible. Each class serves its own unique purpose:

.element-hidden
The role of this class is to hide elements from all users. This class should be used for elements which should not be immediately displayed to any user. An example would be a collapsible fieldset that will be expanded with a click from a user. The effect of this class can be toggled with the jQuery show() and hide() functions.
.element-invisible
The role of this class is to hide elements visually, but keep them available for screen-readers. This class should be used for information required for screen-reader users to understand and use the site where visual display is undesirable. Information provided in this manner should be kept concise, to avoid unnecessary burden on the user. This class must not be used for focusable elements (such as links and form elements) as this causes issues for keyboard only or voice recognition users.

JavaScript variable Drupal.jsEnabled has been removed

In previous versions of Drupal, you could do the following in JavaScript code, to verify that JavaScript was enabled and sufficient for Drupal to do its “behaviors”:

if( Drupal.jsEnabled ) {
// something
}

In Drupal 7, the Drupal.jsEnabled variable is no longer defined, and there is no work-around — the assumption is that JQuery things will simply not work if they don’t work, so there’s no reason to check ahead of time. See issue #444352: Kill the killswitch for discussion.

PHPTemplate suggestion wildcard

(issue) PHPTemplate offers suggestions based on the URI integers. In Drupal 6, you have to theme the previous suggestion or the specific one eg.

page-user.tpl.php or page-user-1.tpl.php

This was cumbersome because to theme all the user pages, it meant overriding page-user.tpl.php, which in turn themed the user login page.

The new suggestion wildcard for integer arguments accepts % suggestions page–user–%.tpl.php. Suggestions which have additional arguments like page–user–edit.tpl.php remain the same; this simply differentiates the suggestions with and without integer args.

Include theme definition explicitly on element when using system_elements()

In system_elements(), it is now necessary to include the theme definition explicitly on the element, rather than allowing the system to “fallback” and assign it automatically. Refer toissue 127731.

Added markup to make installation task progress perceivable with screen-reader and CSS disabled

(Issue)

In D6 there is no markup to indicate which of the installation tasks were complete, or which task is active, these differences are only shown with CSS styling.

In Drupal 7 markup has been added to theme_task_list() to:

Add a heading that is only visible to screen-reader users and when CSS is disabled.
<h2>Installation tasks</h2>
Append text “(done)” and “(active)” to relevant tasks in the task list, visible only to screen-reader users and when CSS is disabled.
<span>(done)</span>

Add an invisible heading to theme_breadcrumb()

(Issue)

In D6 there is no markup to indicate the role or purpose of the breadcrumb links to users of screen-readers.

Drupal 7 provides a heading before the list of breadcrumb links, which is visible to screen-reader users and when CSS is disabled. This heading has been added to theme_breadcrumb() and to garland_breadcrumb().

<h2>You are here</h2>

Changes to alt and title attribute for the RSS feed icon

In D6 the alt attribute of the RSS feed icon themed by theme_feed_icon() was statically set to “Syndicate content” and the title attribute of the icon was set to the string passed to the function in the $title parameter.

Drupal 7 sets the alt attribute of the image and the title attribute of the anchor for the RSS feed to the same text. The text is comprised of “Subscribe to ” + the $title string passed to theme_feed_icon().

In previous versions, the search_box was displayed by the theme using $search_box.

Drupal 7 removes this. The search form is simply part of the block system. Theme developers will want to remove all references to $search_box in the theme, and may need to change CSS to handle the search box in the block.

Site maintainers upgrading sites from Drupal 6 to Drupal 7 will want to add the search form block to their site.

(Issue)

function menu_tree_output() now returns a structured array of data that can be rendered to html using drupal_render().

Function theme_menu_item_link() and theme_menu_item() have been removed and are effectively replaced by in terms of rendering a menu tree by theme_menu_link(). This is the default function used to render each link in the tree returned by menu_tree_output().

Function theme_menu_local_task() takes different parameters and has a companiontheme_menu_local_action() that did not exist in Drupal 6. Both of these function take as the first parameter a menu link array with ‘title’, ‘href’, and ‘localized_options’ keys. In Drupal 6, the first parameter was a string. The change to array was made in order to allow removal of theme_menu_item_link(). The second parameter theme_menu_local_task() of is still a boolean, $active.

Issue: #364219: Navigation menus should be preceded by headings of the appropriate level (usually <h2>).

To meet Web Content Accessibility Guidelines (WCAG) requirements, HTML headings should be used before all content sections, which includes lists of links such as menus. The headers ensure that there is a quick way for assistive technology users to browse through the content; however, most visual users do not need headers on navigation lists, because they can get a sense of the structure by how they are arranged visually on the page. So, the recommendation is to add a header with the “element-invisible” CSS class on it, so that only assistive technology users will notice the header.

It is also important that the header level used (H2, H3, etc.) be appropriately nested in the heading hierarchy. So, it is not recommended to just blindly add an H2 header before each list.

For that reason, the theme_links() function, which is normally called via theme(‘links’, …), has a new third parameter $heading to add the required heading to a list of links.

For example – Drupal 6 in a typical page.tpl.php file:

<?php print theme('links', $secondary_menu, array('id' => 'secondary-menu', 'class' => array('links', 'clearfix'))); ?>

Drupal 7:

<?php print theme('links', $secondary_menu, array('id' => 'secondary-menu', 'class' => array('links', 'clearfix'), 'heading' => array('text' => t('Secondary menu'), 'level' => 'h2', 'class' => array('element-invisible')))); ?>

This will result in a semantically correct and accessible secondary menu in Drupal 7, because an invisible heading has been added:

<h2>Secondary menu</h2>

For more information:

theme_get_setting() and THEME_settings() have been improved

In Drupal 6, themes could add custom form elements to their “configure theme settings” page at admin/build/themes/settings/THEMENAME. Themes would need to create a theme-settings.php page in their theme directory and use a function with the following syntax:

<?php
/**
* Implementation of THEMEHOOK_settings() function.
*
* @param $saved_settings
*   array An array of saved settings for this theme.
* @return
*   array A form array.
*/
function phptemplate_settings($saved_settings) { }
?>

In Drupal 7, much more flexibility is given to themes to modify the entire theme settings form. In a theme’s theme-settings.php, themes should now use aTHEMENAME_form_system_theme_settings_alter(&$form, $form_state) function. This gives the same power to themes that modules have if they use hook_form_system_theme_settings_alter(). See the “Forms API Quickstart Guide” and “Forms API Reference” on http://api.drupal.org/api/7, as well as thehook_form_FORM_ID_alter() docs to learn the full flexibility of Forms API. Note that themes can no longer use the phptemplate_ prefix to the function; you’ll need to use the actual name of your theme as the prefix.

Here’s an example if you had a “foo” theme and wanted to add a textfield whose default value was “blue bikeshed”:

<?php
function foo_form_system_theme_settings_alter(&$form, $form_state) {
$form['foo_example'] = array(
'#type'          => 'textfield',
'#title'         => t('Widget'),
'#default_value' => theme_get_setting('foo_example'),
'#description'   => t("Place this text in the widget spot on your site."),
);
}
?>

In order to set the default value for any form element you add, you’ll need to add a simple line to your .info file: settings[SETTING_NAME] = DEFAULT_VALUE. For our foo theme, you’d need to edit the foo.info file and this line:

settings[foo_example] = blue bikeshed

In any of your theme’s php files, you can retrieve the value the user set by calling:

<?php
$foo_example = theme_get_setting('foo_example');
?>

theme_form_required_marker()

(issue) The markup for generating the marker on required form elements is now handled by a separate function, theme_form_required_marker() instead of just being included as part of the work performed by theme_form_element(). This allows you to reuse this markup in other places or to modify the markup without changing all of theme_form_element()

(issue) The markup for generating a link is now handled by a theme function, theme_link(), instead of being hard-coded into the l() function. This allows you to implement a preprocess function or an override function in order to customize the markup of any link. Doing so may slow down Drupal pages that have many links, so it is recommended to evaluate the benefit vs. the performance trade-off, but the capability exists for sites and themes that need it. This theme function is for customizing the markup of links, generically. Other theme functions exist for customizing links based on context. For example, to customize menu links, override theme_menu_link() instead.

Example of hook_preprocess_link():

<?php
function mytheme_preprocess_link(&$variables) {
// In order to style links differently depending on what they are linking to,
// add classes that contain information about the link path.
if (strpos($variables['path'], ':') !== FALSE) {
// For external links, add a class indicating an external link and a class
// indicating the scheme (e.g., for 'mailto:...' links, add a 'link-mailto'
// class).
$variables['options']['attributes']['class'][] = 'link-external';
$variables['options']['attributes']['class'][] = 'link-' . parse_url($variables['path'], PHP_URL_SCHEME);
}
else {
// For internal paths, add a class indicating an internal link.
$variables['options']['attributes']['class'][] = 'link-internal';
if (empty($variables['path']) || $variables['path'] == '<front>') {
// Add a class indicating a link to the front page.
$variables['options']['attributes']['class'][] = 'link-front';
}
else {
// For internal links not to the front page, add a class for each part
// of the path. For example, for a link to 'admin/structure/block', add
// the classes 'link-path-admin', 'link-path-admin-structure', and
// 'link-path-admin-structure-block'.
$class = 'link-path';
foreach (explode('/', $variables['path']) as $path_part) {
$class .= '-' . $path_part;
$variables['options']['attributes']['class'][] = $class;
}
}
}
}
?>

Example of overriding theme_link():

<?php
function mytheme_link($variables) {
// Place a span within and outside the anchor tag in order to implement some
// special styling.
return '<span><a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '><span>' . ($options['html'] ? $text : check_plain($text)) . '</span></a></span>';
}
?>

(Issue)
To meet Web Content Accessibility Guidelines (WCAG) 2.0 guideline 2.4.1 Bypass Blocks, web pages need to have a link to help keyboard only users and screen readers more easily access the main content of a website.

Garland’s implementation is hidden visually, but keep them available for screen-readers. Furthermore, if a keyboard only user tabs through a site the link will become visible as it gains focus.

To hide the skip navigation you can use one the new classes available to hide content in an accessible manner.

Alter hooks available to themes

(Issue) Hooks that are used to alter content before being displayed on the page are now available to themes. Some important ones to note are:

Note that although technically all of the alter hooks are exposed to the theme, only a given number of them will actually work due to the way the Drupal bootstrap works. If you need to use hook_menu_alter, for example, you’ll have to use a module. These hooks can be exposed in template.php.

Drupal 7.x:

<?php
/**
* Implement hook_page_alter().
*/
function mytheme_page_alter(&$page) {
// Remove elements from the page.
}

/**
* Implement hook_css_alter().
*/
function mytheme_css_alter(&$css) {
// Replace some CSS files with this theme's special CSS.
}
?>

System module stylesheets have been reorganized to separate behavior-supporting styles from presentational styles.

(Issue) Summary of changes:

  • Styles from default.css were merged into system.css and default.css was removed.
  • system-behavior.css was added to house behavior-supporting styles, ie. styles for autocomplete, drag and drop, collapsible fieldsets, progress bars, etc.

New theme setting for displaying the Shortcut module “add to shortcuts” link

Issue: #674394: The add/remove shortcut buttons look bad and don’t appear in most themes besides Seven

In Drupal 7, you will notice that when the Shortcut module is enabled, the core Seven administration theme displays a “plus” or “minus” sign next to the title of each page (for sufficiently privileged users), which allows that page to be added or removed from the user’s set of shortcuts via a one-click link.

The appearance of this link is controlled by a theme setting. If you want it to display in your theme when the Shortcut module is enabled, add the following line of code to your theme’s .info file:

settings[shortcut_module_link] = 1

Specific template overrides of generic templates use a ‘–’ delimiter instead of ‘-’

Issue #678714: Unify use of theme hook / template suggestions, fix clobbering problems, and improve suggestion discovery performance

In Drupal 6, some template files could be overridden in a targeted way. For example, the theme could contain a “node-article.tpl.php” file which would be used for nodes of the article type only. In Drupal 7, these need to be renamed to use a double-hyphen. For example, “node–article.tpl.php”. A single hyphen is still used to separate words: for example, “user-picture.tpl.php” or “node–long-content-type-name.tpl.php”, so the double hyphen always indicates a more targeted override of what comes before the “–”.

Please also see http://drupal.org/update/modules/6/7#theme_hook_suggestions_2 for how this affects preprocess functions if your theme implements those.

CSS files are sometimes loaded with @import, sometimes with LINK tags

(Issue) Prior to Drupal 6, CSS files were added to the page using @import statements inside of STYLE tags. Drupal 6 switched to using LINK tags. With Drupal 7, LINK tags are used when the performance setting to “Aggregate and compress CSS files into one file” is enabled, but @import statements are sometimes used when that setting is disabled. This was needed to work around an Internet Explorer limitation of only being able to load the first 31 tags that add CSS files. See the API documentation for drupal_pre_render_styles() for more details explaining when LINK tags are used and when @import statements are used.

Browser-targeted CSS files can and should be added using drupal_add_css()

(Issue) Drupal 7 adds the ability to specify a ‘browsers’ key when calling drupal_add_css().

Drupal 6:
Garland’s page.tpl.php:

<?php
...
<?php print $styles ? >
<!--[if lt IE 7]>
<?php print phptemplate_get_ie_styles(); ? >
<![endif]-->
...
?>

Garland’s template.php:

<?php
...
function phptemplate_get_ie_styles() {
global $language;

$iecss = '<link type="text/css" rel="stylesheet" media="all" href="'. base_path() . path_to_theme() .'/fix-ie.css" />';
if ($language->direction == LANGUAGE_RTL) {
$iecss .= '<style type="text/css" media="all">@import "'. base_path() . path_to_theme() .'/fix-ie-rtl.css";</style>';
}

return $iecss;
}
...
?>

Drupal 7:
Garland’s template.php:

<?php
...
function garland_preprocess_html(&$vars) {
...
drupal_add_css(path_to_theme() . '/fix-ie.css', array('group' => CSS_THEME, 'browsers' => array('IE' => 'lt IE 7', '!IE' => FALSE), 'preprocess' => FALSE));
}
...
?>

See the API documentation for drupal_pre_render_conditional_comments() for details on the ‘IE’ and ‘!IE’ keys.

It is recommended for themes to always use drupal_add_css() for adding a CSS file, so that Drupal code knows the exact total number of CSS files being added, information that might be needed for working around Internet Explorer’s limitation of only being able to load the first 31 LINK/STYLE tags. [docs updated]

Targeted overrides (suggestions) available for theme_menu_link() and theme_menu_tree()

(issue) In addition to other changes to menu rendering, a Drupal 7 theme can implement a THEMENAME_menu_tree__MENU_NAME() and/or THEMENAME_menu_link__MENU_NAME() function to override theme_menu_tree()/theme_menu_link() for a specific menu. For example, THEMENAME_menu_link__management() would override theme_menu_link() for links within the “Management” menu. This is similar to how “node–article.tpl.php” overrides “node.tpl.php”.

theme_submenu() was removed

(issue) Drupal core does not provide theme_submenu() anymore.

New $title_prefix and $title_suffix template variables

(issue) Templates in Drupal 7 have two new standard variables, $title_prefix and $title_suffix, which are renderable arrays that contain output intended to be displayed before or after (respectively) the main title tag that appears in the template.

All standard templates that potentially have a title (e.g., nodes, blocks, comments, the main page.tpl.php file, etc.) should render these variables. It is important that the variables be rendered even if the title itself is not being displayed, since the variables might contain important data added by modules (for example, contextual links) associated with the template as a whole.

Example (from page.tpl.php):

<?php print render($title_prefix); ?>
<?php if ($title): ?><h1 id="page-title"><?php print $title; ?></h1><?php endif; ?>
<?php print render($title_suffix); ?>

theme_node_form() was removed

(issue) Drupal core does not provide theme_node_form() anymore. Node forms now have a CSS classes of .node-form and .node-TYPE-form for facilicate simple node type specific styling of the node form.

node_get_types() renamed to node_type_get_types()

In template.php, replace:

foreach (node_get_types() as $type => $name) {
unset($settings['toggle_node_info_' . $type]);
}

with:

foreach(node_type_get_types() as $type => $name) {
unset($settings['toggle_node_info_'. $type]);
}

Core themes now contain “package = Core” in their .info files

(issue) Each core theme now contains the line: package = Core in their
.info files. This is a core only property that was added to
to help the Update Manager module identify core modules and themes. It should
not be used in custom or contributed themes.

search-result.tpl.php now uses proper H3 headings for search result titles

(issue) H3 heading elements are now used to wrap each search result title to allow for heading based navigation for keyboard only users (accessibility improvement). This required a change from a DL list to an OL list with changes in two templates – search-results.tpl.php and seach-result.tpl.php.

(second issue) Rendering was pushed to the last possible moment in search results theming, resulting in more changes to these templates and the pre-processing functions. One note: the $type variable is now $module (this variable is not used in the default search result markup).

Drupal 6 markup for search-results.tpl.php:

<dlborder-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; font-size: 12px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; vertical-align: baseline; color: rgb(0, 0, 0); background-position: initial initial; background-repeat: initial initial; "><?php print $type; ?>-results">
<?php print $search_results; ?>
</dl>
<?php print $pager; ?>

Drupal 7 markup for search-results.tpl.php:

<?php if ($search_results) : ?>
<h2><?php print t('Search results');?></h2>
<olborder-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; font-size: 12px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; vertical-align: baseline; color: rgb(0, 0, 0); background-position: initial initial; background-repeat: initial initial; "><?php print $module; ?>-results">
<?php print $search_results; ?>
</ol>
<?php print $pager; ?>
<?php else : ?>
<h2><?php print t('Your search yielded no results');?></h2>
<?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

Drupal 6 markup for search-result.tpl.php:

<dt>
<a href="<?php print $url; ?>"><?php print $title; ?></a>
</dt>
<dd>
<?php if ($snippet) : ?>
<p><?php print $snippet; ?></p>
<?php endif; ?>
<?php if ($info) : ?>
<p><?php print $info; ?></p>
<?php endif; ?>
</dd>

Drupal 7 markup for search-result.tpl.php:

<liborder-top-width: 0px; border-right-width: 0px; border-bottom-width: 0px; border-left-width: 0px; border-style: initial; border-color: initial; background-image: initial; background-attachment: initial; background-origin: initial; background-clip: initial; background-color: transparent; font-size: 12px; margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; vertical-align: baseline; color: rgb(0, 0, 0); background-position: initial initial; background-repeat: initial initial; "><?php print $classes; ?>"<?php print $attributes; ?>>
<?php print render($title_prefix); ?>
<h3<?php print $title_attributes; ?>>
<a href="<?php print $url; ?>"><?php print $title; ?></a>
</h3>
<?php print render($title_suffix); ?>
<div>
<?php if ($snippet) : ?>
<p<?php print $content_attributes; ?>><?php print $snippet; ?></p>
<?php endif; ?>
<?php if ($info) : ?>
<p><?php print $info; ?></p>
<?php endif; ?>
</div>
</li>

The corresponding pre-processing functions for search results have also changed.

The name attribute in a and map elements is invalid

(issue) Due to Drupal 7′s XHTML+RDFa 1.0 doctype (which inherits the HTML 1.1 doctype), the HTML output should be compatible with XHTML 1.1, in particular there should be no nameattribute in the a and map HTML elements.

6.x

<a id="new" name="new">

7.x

<a id="new">

PHPTemplate is now the default theme engine

In Drupal 6, specifying the theme engine in .info files was required:
engine = phptemplate

In Drupal 7, this line is no longer necessary because it is assumed by default. You may safely remove it from your .info file.

Themes using the Smarty engine are not affected, and PHP only themes may still be used by specifying “theme” as the engine:
engine = theme

How to Make a Drupal Theme

Monday, March 14th, 2011

Making a custom Drupal theme is actually quite easy. A Drupal theme is just a few PHP files, a CSS file, and an info file. I prefer the PHPtemplate theme engine (the default one) but you have several choices. See the bottom of this post for a link to the official Drupal Theme Developer’s Guide which has information on other Drupal template engines.

The following information was originally written for Drupal 4.7, but has been updated for Drupal 6 on March 4, 2009.

Navigate to your /themes directory. You should have a theme there called /bluemarine. We will use that as an example.

NOTE: before you edit any files you will copy the theme to another directory and rename it. Your custom themes go in the directory /sites/all/themes/. Details about that come later in this tutorial.

Here is a list of the files in the Drupal 6′s Bluemarine theme:

The Files of a Drupal Theme

  • bluemarine.info — A required file that is new to Drupal 6 which provides information about the theme.
  • page.tpl.php — The main template that defines the content on most of the page.
  • style.css — The CSS file that sets the CSS rules for the template.
  • node.tpl.php — This file defines the content of the nodes.
  • block.tpl.php — Defines the content of the blocks.
  • comment.tpl.php — Defines the content of the comments.
  • logo.png — Your logo, if you are using one.
  • screenshot.png — This is a screenshot of your theme that is used in the admin panel and in the user account settings if you have enabled more than one theme so that visitors can choose which theme they want to use.
  • box.tpl.php — puts a box around things like comments. See also http://drupal.org/node/11814.
  • style-rtl.css — this file is new to Drupal 6′s Bluemarine. I think it’s a CSS for right to left languages and can be ignored if you’re using a left-to-right language like English.

page.tpl.php and style.css

The page.tpl.php and style.css files are the main files for your Drupal theme. The page.tpl.php is a mix of HTML and PHP. Look at the file and notice which snippets of PHP are used where. For example, the following snippet from the page.tpl.php file inserts the site’s <head> information. Just copy that snippet into your own custom Drupal template.

<head>
  <title><?php print $head_title ?></title>
  <?php print $head ?>
  <?php print $styles ?>
  <?php print $scripts ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyle Content in IE */ ?> </script>
</head>

The following code from the Bluemarine page.tpl.php file use PHP if statements to print out optional information such as primary links, secondary links, and site slogan. You control whether those display in the Drupal control panel. The Bluemarine template uses tables, but you can easily remove the tables and make it a 100% CSS-based template.

<table border="0" cellpadding="0" cellspacing="0" id="header">
  <tr>
    <td id="logo">
      <?php if ($logo) { ?><a href="<?php print $base_path ?>" title="<?php print t('Home') ?>">
<img src="<?php print $logo ?>" alt="<?php print t('Home') ?>" /></a><?php } ?>
      <?php if ($site_name) { ?>
<h1 class='site-name'><a href="<?php print $base_path ?>"
title="<?php print t('Home') ?>"><?php print $site_name ?></a></h1><?php } ?>
      <?php if ($site_slogan) { ?><div class='site-slogan'><?php print $site_slogan ?></div><?php } ?>
    </td>
    <td id="menu">
      <?php if (isset($secondary_links)) { ?>
<div id="secondary"><?php print theme('links', $secondary_links) ?></div><?php } ?>
      <?php if (isset($primary_links)) { ?>
<div id="primary"><?php print theme('links', $primary_links) ?></div><?php } ?>
      <?php print $search_box ?>
    </td>
  </tr>
  <tr>
    <td colspan="2"><div><?php print $header ?></div></td>
  </tr>
</table>

The Drupal styles.css File

The style.css file is straightforward. I recommend the Firefox Web Developer Toolbar for creating the style.css file. Use the toolbars option Display ID & Class Details in the Information menu to view the CSS classes and ID’s that Drupal is generating. Then add your own CSS rules to the style.css file.

Other Drupal Theme Files

Other files in the Drupal theme are block.tpl.php, box.tpl.php, comment.tpl.php, and node.tpl.php. Each one controls the layout of certain parts of the template. The comment.tpl.php defines the comment layout as shown below. It is fairly straightforward PHP: “If there is a user picture, print the user picture, etc.

  <div class="comment<?php if ($comment->status == COMMENT_NOT_PUBLISHED) print ' comment-unpublished'; ?>">
    <?php if ($picture) {
    print $picture;
  } ?>
<h3 class="title"><?php print $title; ?></h3>
<?php if ($new != '') { ?><span class="new"><?php print $new; ?></span><?php } ?>
    <div class="submitted"><?php print $submitted; ?></div>
    <div class="content"><?php print $content; ?></div>
    <div class="links">&raquo; <?php print $links; ?></div>
  </div>

Your First Custom Drupal Theme

Just make a copy of the default Bluemarine template and put it in your Drupal /sites/all/themes/ directory. That directory doesn’t exist by default, so you should create it if you haven’t already. See the README file in /sites/all/ for more information. Rename the copy of Bluemarine to the name of your new theme. Enable the new theme.

NOTE: In Drupal 6 there are also theme info files. To change the name of the theme you’ll also need to change the name in the bluemarine.info file:

; $Id: bluemarine.info,v 1.4 2007/06/08 05:50:57 dries Exp $
name = Bluemarine
description = Table-based multi-column theme with a marine and ash color scheme.
version = VERSION
core = 6.x
engine = phptemplate

Then strip most of the HTML out of the page.tpl.php file and replace it with the HTML that you would like for your theme. Leave the PHP, modifying it as desired. If you are using Linux for Web development, you can use Quanta Plus as an editor to edit your template files directly on the server. Each time you save the file in Quanta Plus, the remote copy of the file will be updated.

Use the Firefox Web Developer Toolbar’s Display ID & Class Details feature to view CSS information on your new template that you are viewing the the browser. Either start a new style.css file from scratch, or modify the existing one to get the template the way you would like. To edit the display of blocks, nodes, and comments, edit the block.tpl.php, node.tpl.php, and comment.tpl.php files respectively.

When you are finished with your template, take a screenshot and resize it to about 150×90 pixels. Upload it to your theme directory as screenshot.png.

Drupal Template Variables

The PHP snippets in the examples above are just printing PHPtemplate variables. A complete list of available PHPtemplate variables that you can use in your template can be found on Drupal.org’s PHPtemplate variables page. Below are the available variables from 24 July 2007:

$breadcrumb
HTML for displaying the breadcrumbs at the top of the page.
$closure
Needs to be displayed at the bottom of the page, for any dynamic javascript that needs to be called once the page has already been displayed.
$content
The HTML content generated by Drupal to be displayed.
$directory
The directory the theme is located in , e.g.
themes/box_grey or themes/box_grey/box_cleanslate.
$footer_message
The footer message as defined in the admin settings.
$head
HTML as generated by drupal_get_html_head().
$head_title
The text to be displayed in the page title.
$help
Dynamic help text, mostly for admin pages.
$is_front
True if the front page is currently being displayed. Used to toggle the mission.
$language
The language the site is being displayed in.
$layout
This setting allows you to style different types of layout (‘none’, ‘left’, ‘right’ or ‘both’) differently, depending on how many sidebars are enabled.
$logo
The path to the logo image, as defined in theme configuration.
$messages
HTML for status and error messages, to be displayed at the top of the page.
$mission
The text of the site mission.
$node
(5.x and after only)If you are in page.tpl.php displaying a node in full page view then $node is available to your template.
$onload_attribute
(4.7 and older only) Onload tags to be added to the head tag, to allow for autoexecution of attached scripts.
$primary_links (array)
An array containing the links as they have been defined in the phptemplate specific configuration block.
$scripts
(5.x and after only) HTML to load the JavaScript files and make the JS settings available. Previously, javascript files are hardcoded into the page.tpl.php
$search_box
True(1) if the search box has been enabled.
$search_button_text
(4.7 and older only)Translated text on the search button.
$search_description
(4.7 and older only)Translated description for the search button.
$search_url
(4.7 and older only)URL the search form is submitted to.
$secondary_links (array)
An array containing the links as they have been defined in the phptemplate specific configuration block.
$sidebar_left
The HTML for the left sidebar.
$sidebar_right
The HTML for the right sidebar.
$site
The name of the site, always filled in.
$site_name
The site name of the site, to be used in the header, empty when display has been disabled.
$site_slogan
The slogan of the site, empty when display has been disabled.
$styles
Required for stylesheet switching to work. This prints out the style tags required.
$tabs
HTML for displaying tabs at the top of the page.
$title
Title, different from head_title, as this is just the node title most of the time.

There are also other variables available for your Drupal theme. A good list can be found in Chapter 8 of the essential book Pro Drupal Development. I believe that Chapter 8 is a free sample download.

Also check out these two books from Packt Publishing: Drupal 5 Theming and Building powerful and robust websites with Drupal 6.