18.10.2016 Views

Drupal 7 Module Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Drupal</strong>’s Theme Layer<br />

A <strong>Drupal</strong> theme is normally composed of CSS, images, JavaScripts, template files<br />

(discussed shortly), a .info file, and a template.php file. The template.php file<br />

is analogous to a module's .module file. It contains all of the PHP functions for the<br />

theme and is automatically loaded when the theme is initialized.<br />

If a theme wants to override a particular theme function, it needs to copy the theme<br />

function from its original location and paste it into its template.php file. Then it<br />

needs to change the function's prefix from theme to its own name and finally, it<br />

needs to start making the desired changes to the function.<br />

For example, if the Bartik theme wants to override the theme_menu_local_tasks()<br />

function in order to add some markup around the page's tabs, it would copy the<br />

entire function from includes/menu.inc, paste it into Bartik's template.php, and<br />

rename it to bartik_menu_local_tasks().<br />

Fortunately, when a theme overrides a default theme function, a module's preprocess<br />

functions continue to work as normal.<br />

Themes also have the ability to create preprocess functions. If the Bartik theme<br />

decides to format a user's name in "last name, first name" format, it can implement<br />

a bartik_preprocess_username() function. Fortunately, a theme's preprocess<br />

functions do not override a module's preprocess functions. All preprocess<br />

functions are run; first any module's preprocess functions and then the theme's<br />

preprocess function.<br />

Template files<br />

While theme functions might be the easiest for module developers to understand,<br />

template files are the easiest for themers to grasp. When a theme hook is implemented<br />

with template files, they are used instead of theme functions. However, from a module<br />

developer's standpoint, there is actually a remarkable amount of similarity between<br />

template files and theme functions. First, let's take a closer look at template files.<br />

Templates are files primarily containing HTML but with some PHP statements<br />

mixed in using the template's variables. Instead of declaring a theme_hook_name()<br />

function, a module would instead create a hook-name.tpl.php file. The following<br />

are the contents of a typical template file, typical-hook.tpl.php:<br />

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!