Build a new theme for Drupal 7

Source: Internet
Author: User
Tags alphabetic character php print php source code php template tidy drupal

The topic explains the user interface (UI) of the Drupal Web site. Although the theme structure has not changed significantly, Drupal version 7 comes with a new approach to implementing the theme. This article demonstrates how to create a new Drupal 7 theme.

The goal of the Drupal theme is to separate the processing logic and design elements of the framework. To do this, Drupal employs a complex theme system that includes themes, theme engines, and hooks. The theme component works with the Drupal core system and module design elements to create a user interface that has a unique look (separate Drupal pages and forms). By separating Drupal's business logic from its presentation logic, the code is easier to maintain, and you can swap out the implementation of the topic layer without rewriting the code layer, and vice versa. Figure 1 illustrates the DRUPAL framework structure.

Figure 1. Drupal Framework Structure

The topic shows Drupal core data extracted from the database by the underlying theme engine, which is used as an interface between the Drupal core and the subject template.

Theme Engine

The theme engine is a means by which the theme interacts with the Drupal core through this engine. There are several theme engines that can be used in conjunction with Drupal. The most popular are:

    • PHPTemplate
    • XTemplate
    • Plain PHP
    • Smarty Engine
Other Drupal theme Engines

There are several other commonly used theme engines in conjunction with Drupal. They include PHPTAL , wgSmarty zengine, Awesomengine, ETS, Haml, XSLengine and peroxide. However, this article uses the PHPTemplate engine because it is the default theme engine and is the only theme engine packaged with Drupal 71.

If you prefer, you can also use your own custom engine.

PHPTemplateThe theme engine is the default Drupal engine and the theme engine used in this article, which uses a separate theme file with the name similar to filename.tpl.php as the theme of the Drupal theme_filename() function. Each of these files contains HTML frames for dynamic Data and PHP statements. Therefore, with PHP's basic knowledge, it PHPTemplate is easy to create advanced topics, as this involves only a very small amount of code.

Back to top of page

Planning topics

The theme is composed of several file components. The number of files depends on the complexity of the theme. A theme may have only three files, or there may be dozens of files, including graphic elements and various scripts placed in several folders within the theme directory. Figure 2 shows typical file descriptions (colors, images, logos, templates, styles, and PHP files) that are expected to be found in the main theme folder.

Figure 2. Typical contents of a theme folder

Not all of these files are required for a theme, and many people think that cascading style sheets (CSS) files are absolutely necessary, but some themes don't even have CSS. By understanding the usage of these theme files, the topic structure and how it works will become clearer. Let's look at some of the files in the topic directory and explore their functionality in the overall theme.

. info file

The. info file is a required file: Drupal must include it to see the topic. The. info file tells the internal name of the Drupal topic. For example, if the name of this file is, then the name Drupal gives to this topic will be ibmtheme. If your theme uses elements such as JavaScript, metadata, style sheets, or block regions, you must also define them in the. info file. Everything is optional. In Listing 1, the content of the. info file for the Bartik topic explains this behavior.

Listing 1. Content of the. info file for the Bartik theme
; $Id:,v 1.5 2010/11/07 00:27:20 dries Exp $name = Bartikdescription = A flexible, recolorable theme with many R Egions.package = Coreversion = Versioncore = 7.xstylesheets[all][] = css/layout.cssstylesheets[all][] = css/ Style.cssstylesheets[all][] = css/colors.cssstylesheets[print][] = Css/print.cssregions[header] = Headerregions[help ] = helpregions[page_top] = page Topregions[page_bottom] = page bottomregions[highlighted] = highlightedregions[featured ] = featuredregions[content] = Contentregions[sidebar_first] = Sidebar Firstregions[sidebar_second] = Sidebar Secondregions[triptych_first] = Triptych Firstregions[triptych_middle] = Triptych Middleregions[triptych_last] = Triptych Lastregions[footer_firstcolumn] = Footer First Columnregions[footer_secondcolumn] = footer Second Columnregions[footer_thirdcolumn] = footer Third Columnregions[footer_fourthcolumn] = footer Fourth columnregions[ Footer] = Footersettings[shortcut_module_link] = 0; Information added by packAging script on 2011-01-05version = "7.0" project = "Drupal" datestamp = "1294208756" 
. tpl.php Template File

The theme directory contains several template files with filenames such as xxx.tpl.php. These template files contain extensible HTML (XHTML) tags and PHP variables for the theme. In some cases, you can write them to provide other types of data output, such as RSS. In general, each Drupal theme's tpl.php files are encoded to handle specific data output: Embedding complex logic in template files can be confusing and counterproductive, as it may make them difficult to maintain. The ideal scenario is to have them contain only simple XHTML markup and PHP variables.

Listing 2 shows the contents of the node.tpl.php file, which describes the output of the base node of the core Garland topic.

Listing 2. Garland content of the theme node.tpl.php file
<?php//$Id: node.tpl.php,v 1.24 2010/12/01 00:18:15 webchick Exp $?><div id= "node-<?php print $node->nid;   ?> "class=" <?php print $classes;?> "<?php print $attributes;?>> <?php print $user _picture;?> <?php Print render ($title _prefix),?> <?php if (! $page):?> template.php file

The template.php file typically contains all the conditional logic and data processing for the topic output. You can also use the template.php file to keep your theme's. tpl.php files tidy. Because this is a PHP file, forcing the markup to open in PHP <?php as the beginning of the content, but you can omit the end tag.

Other files

There are several other elements that are not required for a theme to work properly, but they may appear in many topics. These elements include logos and screens, theme-settings.php files, and files:

  • Logos and screens. These elements are recommended elements, but are not absolutely necessary for the normal operation of the theme. However, if you want to contribute a topic to the Drupal repository, the screen is a mandatory element. Figure 3 is the screen for the Garland theme. Figure 3. Garland screen of the theme
  • theme-settings.php. In addition to general settings such as search or task logos, the file also displays UI management settings or advanced features. Please review the contents of this file for the Garland topic, as shown in Listing 3, which shows the final display. Listing 3. Garland contents of the theme-settings.php file
    <?php//$Id: Theme-settings.php,v 1.3 2010/09/04 15:21:09 dries Exp $/** * @file * Theme setting callbacks for the Garl and theme. *//** * Implements hook_form_form_id_alter (). * * @param $form * The   form. * @param $form _state * The   form state. */function Garland_form_system_theme_settings_ Alter (& $form, & $form _state) {  $form [' garland_width '] = Array (    ' #type ' = = ' radios ',    ' #title ' = > t (' Content width '),    ' #options ' = = Array ('      fluid ' = ' t (' fluid width '),      ' fixed ' = = t (' fixed Width '),    ' #default_value ' = theme_get_setting (' garland_width '),    ' #description ' and ' = ' (' Specify whether the content would wrap to a fixed        width or would fluidly expand to the width of the browser window. '), c12/>//Place this above the color scheme options.    ' #weight ' = 2, '  );}

    The final display will be a form similar to Figure 4.

    Figure 4. Theme Settings page
  • color. Module's function is to allow administrators to completely change the theme of the color scheme, without having to manually modify the style sheet. If your theme requires color-matching module support, you must include a color directory that contains the file and various support files.

Back to top of page

Building a Theme

There are two basic ways to build a theme: You can build it from scratch, or you can modify an existing theme. In this article, you will build a new theme from the beginning. That being said, you should also have the content of your existing topic ready to understand the structure.

Create a directory structure

First, create a directory that contains the theme files. The best place to place this directory is the Sites/all/themes directory. Name the directory to describe your topic: the name should not contain spaces.

Although not mandatory, this is helpful for creating subdirectories for style sheets (CSS files), images, and scripts (if your theme uses them). Doing so helps keep the structure tidy.

Back to top of page

Building an. info file

An. info file is just a text file that contains data, usually a parameter that describes the structure, content, and configuration of the topic. In the text file, each row has a key-value pair, the value is placed to the right of the equal sign ( = ), and the key is placed to the left of the equal sign. Listing 4 provides an example.

Listing 4. Example contents of an. info file from a Garland theme
; $Id:,v 1.10 2010/11/07 00:27:20 dries Exp $name = Garlanddescription = A multi-column theme that can be confi Gured to modify colors and   switch between fixed-and fluid-width layoutspackage = coreversion = Versioncore = 7.xstyle Sheets[all][] = style.cssstylesheets[print][] = print.csssettings[garland_width] = fluid; Information added by packaging script on 2011-01-05version = "7.0" project = "Drupal"

You can add a comment by using a semicolon () at the beginning of a line ; . When you use square brackets ( [] ), you are creating an array of associated values. Let's take a detailed description of the elements that must or might be included in the. info file.


nameThe value is required. It should be a human readable name that must begin with an alphabetic character. The limitation of the name is the same as the limit of the constituent function in PHP, because Drupal uses it for the same purpose. Therefore, the name can contain numbers and underscores ( _ ), but there are no hyphens ( - ), spaces, or punctuation marks. Here's the syntax:

Name = Garland

descriptionThe key is recommended, it should only be a brief description of the subject. The description you enter here appears on the selection or appearance page of the topic. Here's the syntax:

Description = A Multi-column theme that can is configured to modify colors and   switch between Fixed-and fluid-width l Ayouts

screenshotThe key is optional. Its function is to tell Drupal where to find thumbnails of new topics. Thumbnails are also displayed on the appearance page. If the key is not included in the. info file, Drupal will invoke the Screenshot.png file in the default theme directory. If you decide to call the thumbnail file name that is not screenshot.png, or if you place the file in a directory other than the theme home directory, you will need to include this key. Here's the syntax:

Screenshot =/images/screenshot.png

To create a screen, simply capture the full theme image in the browser. Then, crop the image and resize it to 294 x219 pixels, saving it as screenshot.png. Place the file in the same folder as the. info file.


Although many popular themes include the version key, we do not encourage the use of it. If you're going to host a theme in the Drupal theme repository, there's no need to include it version , because when a release is packaged for download, automatically adds a version string. Otherwise, you can include any version string you like. Here's the syntax:

Version = 1.0

coreThe key is a required value. In all currently supported Drupal versions, you must describe the version of Drupal that is compatible with your modules and themes. The value set here will be compatible with the Drupal Core compatibility constant, which can be found in the Include/ file, and Drupal will disable the theme if no match is found. The following is the syntax for this constant:

<?phpdefine (' drupal_core_compatibility ', ' 7.x ')?>

The packaging script automatically sets this value based on the Drupal core compatibility settings on each publishing node (if you contribute your theme).


engineKey represents the kind of theme engine used by your theme. In most cases it is required. If you do not provide it in the. info file engine , Drupal assumes that the topic is a separate theme that is implemented through the. theme file. Most of the topics found in the library use the default PHPTemplate engine, which is packaged with the Drupal core. Here's the syntax:

Engine = Phptemplate
Basic topics

If your theme is a sub-topic of another topic, be sure to declare it to base theme enable theme inheritance. In other words, the child theme will be able to use the underlying theme (base theme) file resource. You need to enter the internal machine-readable name of the underlying theme. Here's the syntax:

Base theme = Garland
Zone to create a new topic area

Any part of the page that you want to be able to edit on the Blocks Administration page needs to be a region. Typically, this area includes the title, right column, content area, and footer. You must introduce all of your regions in the. info file. Otherwise they don't exist for Drupal.

regionsThe key defines the block areas available for the theme. You must explicitly define the regions key and then define the internal machine-readable name in square brackets. After that, you must define the human readable name as the appropriate value. Here's the syntax:

Regions[highlighted] =mission Statement

If you choose not to define a region, the following values are assumed in the Drupal 7 topic:

Regions[header] = headerregions[highlighted] = Highlightedregions[help] = helpregions[content] = Contentregions[ Sidebar_first] = left Sidebarregions[sidebar_second] = right Sidebarregions[footer] = Footer

You can override these values to suit your specific needs. If you do this, you must declare the row. Here's the syntax:

Regions[highlighted] =mission Statement

You can toggle the various page elements on the configuration page of the topic. The check boxes displayed on the topic Configuration page are controlled by the features key (see Figure 5). Therefore, for elements that are not defined or used by the theme, you can suppress the display of their check boxes. If you omit an entry, the check box for that attribute is suppressed, and if you do not define any attributes, all of the check boxes will be displayed as default values that are assumed.

Figure 5. Theme Properties Settings page

Listing 5 shows features all the available elements of the key.

Listing 5. Topic attribute entries in the. info file
Features[] = logofeatures[] = namefeatures[] = sloganfeatures[] = node_user_picturefeatures[] = Comment_user_picturef Eatures[] = faviconfeatures[] = main_menufeatures[] = Secondary_menu
Style sheet

Drupal themes have used style.css by default. However, in the current release, if STYLE.CSS is not specified in the. info file, the topic no longer defaults to STYLE.CSS. In addition, you can add a new style sheet through an. info file. Here's the syntax:

Stylesheets[all][] = css/style.cssstylesheets[print][] = css/print.css

In the topic's template.php file, drupal_add_js() It was common practice to include JavaScript files by calling functions such as these. However, in Drupal 7, the file is only included when you specify Script.js in the. info file. Here's the syntax:

scripts[] = Scripts/myscript.js

The string you define here will be the minimum PHP version supported by the theme. The default value comes from a DRUPAL MINIMUM PHP constant (located in the Includes/ file):

<?phpdefine (' drupal_minimum_php ', ' 5.2.4 ')?>

You can change this value, but you do not need to add a string. Here's the syntax:

php = 5.2.4
The default. Info value

The. info file contains the default values that Drupal assumes for each installed theme. If these values are not defined in the. info file, Drupal forces the theme to use the default values. However, note that these values are applied as a group. This means that if you rewrite a line, such as:

Regions[sub_header] = Sub-header

You will need to redefine the rest of the default zone; otherwise, they will be omitted. This rule also applies to style sheets. Even if a style sheet is not technically defined in a group, you must redefine style.css again if another style sheet is defined in the. info file, otherwise it will not be included.

The keys and values in Listing 6 are the default values for the Drupal 7 topic.

Listing 6. The default. Info value
Regions[sidebar_first] = left  Sidebarregions[sidebar_second] = right Sidebarregions[content] = contentregions[ Header] = Headerregions[footer] = footerregions[highlighted] = Highlightedregions[help] = helpregions[page_top] = page to  Pregions[page_bottom] = page Bottomengine = phptemplatefeatures[] = logofeatures[] = namefeatures[] = sloganfeatures[] = node_user_picturefeatures[] = comment_user_picturefeatures[] = faviconfeatures[] = main_menufeatures[] = Secondary_ Menuscreenshot = Screenshot.png

Back to top of page

Building the page.tpl.php file

Now, study the contents of a typical page.tpl.php file. The image in Figure 6 comes from the Garland theme, showing how the source code looks in the browser.

Figure 6. page.tpl.php source code in the browser

If you look more closely, the page.tpl.php template is just a simple HTML page with a large number of PHP statements. Very handy, most PHP elements have been defined for Drupal, and all you need to do is place them as needed.

Note: the link [Core Templates] will provide you with a list of variables available for the page.tpl.php template.

Add a variable to a basic page element

There are several variables that can be used to build a page.tpl.php. Choose which variables to include, depending on the features you want to implement in the topic. For example, if you choose to have breadcrumbs on your Web page, add a $breadcrumbs variable.

The most common variables in page.tpl.php are:

    • $site_name
    • $logo(The logo uploaded by the theme setting; only used when implementing the logo theme feature)
    • $title(page title)
    • $main_menu
    • $secondary_menu
    • $breadcrumbs(Navigation aids, leaving a string of reference links when users go deeper into the site)

Drupal management also has variables related to:

    • $tabs(Used to edit or view menus such as management menus; often used by modules)
    • $messages
    • $action_links

Some of the other useful variables are:

    • $base_path(Path to site root)
    • $front_page(The path of the site home page)
    • $directory(The path to your theme)

Insert the variable using the Render application Programming Interface (API), as follows:

<?php print render ($tabs);?>

If your PHP and HTML skills are high, you can obviously create your own excellent theme by observing how the sample is built and then using the allowed variables.

Back to top of page

Build additional template file printing or rendering

Some variables need to be render() displayed using functions, while others can be printed in a simple way. If the array contains variables listed in the Page.tpl.php reference page (see Resources for links), you need to use the render() method. Otherwise, you can print the variable ( <?php print $variable; ?> ).

The default templates for other available theme files are available with the Drupal core. You can find a list of them at the Drupal site (see Resources for a link). For page.tpl.php files, it's a good way to easily build your own files by finding a core file, observing how it's composed, and then building your own. Visiting the Drupal site will point you to the variables that are allowed for use in any theme file.

Back to top of page


In a normal static HTML page, you must include a pointer in the header to indicate the location of the style sheet used for the page display. The pointer looks like this:

<link rel= "stylesheet" type= "Text/css" href= "/model.css"/>

As mentioned earlier, you can add a new style sheet to a theme, or you can override the default style. In both cases, you must enter a theme style sheet in the. info file. What's in the style sheet? The modular approach you use for CSS classes is the same as the modular approach that Drupal core uses for standard page elements of the framework. Even though theme developers can create their own classes, there are many classes throughout the Drupal site. For a complete list of the classes in the Drupal 7 core, please refer to resources.

Back to top of page


This article gives you an overview of how the theme system works in Drupal 7, describes several components of the Drupal theme, and how to PHPTemplate build a new theme from scratch using the default theme engine. Now that you've seen the typical structure of each component's theme file, you should know the skills you need to create a custom theme. Start doing what you love!

Note: Original link:

Build a new theme for Drupal 7

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.