Drupal 7 Useful Theme Snippets

Theming a Drupal 7 site can be quite tricky at times. Drupal has a powerful engine for themes and tons of different settings in it. Here's a couple of different code snippets to ease your theme development.

Load different page.tpl.php depending on node type

function ThemeName_preprocess_page(&$vars, $hook) {
	if (isset($vars['node'])) {
		$vars['theme_hook_suggestions'][] = 'page_'. $vars['node']->type;

This goes in your theme's template.php. Replace ThemeName with your theme's name. What this does, is that it takes the current node type's machine name and appends it to the filename of page.tpl.php. As in, if you have node type called blog, it appends that to the filename so it will look for page-blog.tpl.php. Note that this is only a suggestion, if it can't find that file, it will use the regular page.tpl.php.


Load a block to your page.tpl.php or node.tpl.php

$block = block_load('block', '5');
$output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
print $output;

With this snippet, you can load a block straight to your theme. The first line loads the block information, in this case it loads a normal block with id of 5. If you want to f.ex. load the search module, you can type:

$block = block_load('search', '0');

And this will the search form.

The second line renders the block and third line prints it to the theme.


Add Javascript file to your theme

Currently there is two ways to do this. More standard way to do it is to add this line to your .info -file in theme.

scripts[] = name_of_script.js

This will automatically load name_of_script.js in your theme in all pages. To add more scripts, just create a new line just like before.

The other way to add it is to write this in your template.php:

function ThemeName_preprocess_html(&$variables) {
	$options = array(
		'group' => JS_THEME,
	drupal_add_js(drupal_get_path('theme', 'ThemeName'). '/name_of_script.js', $options);


Target theme's frontpage

Sometimes you don't want to make page-front.tpl.php just for small style changes. Instead, you can try doing this in your page.tpl.php:

if (drupal_is_front_page()) {
	$class = "front";
} else {
	$class = "";

print "<body class='".$class."'>";

This adds a class to your body, so now in CSS, you can target stuff like:

#header {
	background: blue;

.front #header {
	background: lightBlue;



Add new comment