Drupal Tutorials

Drupal theming tips and tricks

This tutorial requires you have basic to intermediate knowledge of Drupal theming, basic knowledge of PHP and an understanding of HTML and CSS.

In the overriding theme functions tutorial we touched on using a template.php file within your theme and hopefully you saw how powerful it can be for theming overriding, so I’ll show you a few tips and tricks I have learnt here and there.

1) Organise your code

Keep your template.php file neat and tidy by using structure, include files and commenting.

I know what it’s like when your theming your site you just want to add the code and check out the results. Before long you code is a mess with functions all over the place, no commenting and no structure and you don’t have a clue what any of it does. A few simple sets can help keep your code in a neat and organised manner.

Structure your template.php code into a manner that makes sense to you, something a simply as grouping similar functions in the same area of the code or grouping all your theme override function together in one place.

Include Files
If you find your template.php file is getting huge then consider using include files to help your organisation and structure. By this I mean putting some code from your template.php file into a separate file or files and then loading it in from your template.php file.

require_once dirname(__FILE__).'/template.inc.php';

An example might be putting all your functions that are related to users (ie. theme_username or custom profile functions) in one include file called user.inc, that way if you want to edit any user functions you know exactly where the functions are. This is a very similar approach to how Drupal core works, take a quick look in your “includes” folder to see what I mean.

This technique of using include files does add small loading overheads but one or two includes won’t clog your site but don’t go mad.

Ever written or borrowed a great bit of code and then gone back to it 6 months later and thought “what the hell does that do?”? Well it happens to all of us coders and it’s why it’s so important to spend a few extra minutes on your code commenting it so you know what does what and why. It’s also a great habit to get into for whatever type of coding you’re doing being it Drupal, custom PHP or Java.

You don’t have to write an essay for your comments just a brief description of what the function does, any special notes your likely to forget and in some cases what parameters the function is expecting. If you’re just overriding theme modules you could just copy and paste the comment written in the module that provides the function.

Here are a couple of examples of commenting in PHP (Drupal).
Single line comment

//my comment goes here
Block of comment
* my comment goes here

No excusing for messy code now!

2) Separate your theme CSS files

Drupal by standard will load your themes style.css file but can load in more CSS files at theme level using Drupals drupal_add_css function like so:

= path_to_theme();
drupal_add_css($path ."/node-style.css", 'theme', 'all', false);

CSS aggregator By adding additional CSS files you can keep your Drupal styling (ie. tables, status messages and block style) separate from any custom CSS code you have written like for your layout and design CSS code and this keeps everything more manageable.
I normally have the following CSS files in my themes:
style.css – contain the default Drupal style
layout.css – contains all my CSS layout code
node-style.css – contains CSS code related to my node styling

Loading additional CSS files may slow your site a little so remember to turn on Drupals CSS aggregator once you put your site live.

3) Edit and existing theme

Drupals Creative Commons licence means you are free to take any of the themes in the Drupal theme repository and modify and then use them on your site.
So rather than writing themes from scratch find an existing theme similar to what you want to create and modify it.
Although you are free to this it always nice to credit the original theme creator on your site and don’t try and pass it off as your work, it’s just not on!

4) Use flexible column layouts

This is a great trick I learnt from the Garland theme that dynamically sets a class attribute on the HTML body tag in your page.tpl.php file based on whether your sidebars content any content or not. By setting the CSS class on the body tag you can hide columns depending if they do or don’t contain any content.

For example Drupal lets you assign blocks to regions on your site like your side columns. However imagine on one page of your site you want to hide all the columns so you change the block visibility in the blocks admin area, which should do it! Nope, the blocks are gone but the layout columns are still showing and this is how are template.php file can help by checking if your side bars have content or not.

Here are some example CSS classes you could assign to the body tag:
No-sidebars – neither sidebar has content so should be hidden
Sidebars – both sidebars contain content so should be shown
Left-sidebar – The left sidebar only contains content so should be shown

Tie this all together with some simple CSS code (see below) and you’ll have a dynamic and flexible CSS layout that adjusts itself to your content.

Lets take a look at how the Garlanc theme does this. There are three files involved in this; style.css for the CSS code, page.tpl.php for calling the worker function (phptemplate_body_class) and provides the HTML layout and lastly template.php of course which contains the worker function that decides what class to assign to the body tag.


<body<?php print phptemplate_body_class($sidebar_left, $sidebar_right); ?>>


/* With 3 columns, require a minimum width of 1000px to ensure there is enough horizontal space. */
body.sidebars {
  min-width: 980px;
/* With 2 columns, require a minimum width of 800px. */
body.sidebar-left, body.sidebar-right {
  min-width: 780px;

/* So we move the #center container over the sidebars to compensate */
body.sidebar-left #center {
  margin-left: -210px;
body.sidebar-right #center {
  margin-right: -210px;
body.sidebars #center {
  margin: 0 -210px;

/* And add blanks left and right for the sidebars to fill */
body.sidebar-left #squeeze {
  margin-left: 210px;
body.sidebar-right #squeeze {
  margin-right: 210px;
body.sidebars #squeeze {
  margin: 0 210px;


* Sets the body-tag class attribute.
* Adds 'sidebar-left', 'sidebar-right' or 'sidebars' classes as needed.
function phptemplate_body_class($sidebar_left, $sidebar_right) {
  if (
$sidebar_left != '' && $sidebar_right != '') {
$class = 'sidebars';
  else {
    if (
$sidebar_left != '') {
$class = 'sidebar-left';
    if (
$sidebar_right != '') {
$class = 'sidebar-right';

  if (isset(
$class)) {
' class="'. $class .'"';

You could also use this technique for your homepage layout to hide or show elements of your site depending on whether a user is viewing your homepage or not. Using Drupal’s drupal_is_front_page function you could set the body class attribute to say “front” and then adjust your CSS accordingly.
Here’s a quick bit of code you can add to your phptemplate_body_class function:

if (drupal_is_front_page()) {
$class = 'front';


Ok that concludes my theming tips and tricks for this tutorial but I’m sure I’ll come up with more so keep checking back.
I these weren’t groundbreaking but they are things that I have found useful and that I actual use in my sites so I hopefully some of you will them useful!

Thanks for reading, please feel free to leave any comments below.

Commenting on this Tutorial is closed.


Comments (22)

carmel's picture

Thinking about the second point and if it helps, I like include at least one reset.css to reset all styles, and some others like typography, navigation and form … you know.
It’s very helpful for me, moreover at maintenance “time”...

Freelance's picture

Using include files for views overrides was the way to go in drupal 5 in order to avoid insanity, although in d6 is not as necessary, it is definitely something to keep in mind.

As for separating stylesheets, I would recommend this if you have different and distinct sections on your site that have a lot of CSS in them, will make your life easier.

Also, implementing your own variables for layout, even within special content types, and/or taking advantage of the body classes will get you a very long way without having to tweak too much code.

Great tips!

One of the reasons I like using drupal is because I can sliding doors change the theme on my website very easily.

Thanks for this help :)

Naruto Shippuden

webgal's picture

I have started using drupal and theme setting is something which I am learning by trial and error.So I am finding this article handy.
Types of Plants

Would like to read more, because I would like to create a website for my pest control service company

Hey there, once again a resource we can bank on, thank you once again..
web hosting

This is a great inspiring article.I am pretty much pleased with your good work.You put really very helpful information

casino en ligne

I have started using drupal and theme setting …everything goes perfect.

Very nice tricks. This were very helpful to me as I am new to Drupal, like the idea of editing the existing theme. Thanks for sharing these tips. Regards, David from Web Development

Thanks for sharing this information. I really like your way of expressing the opinions and sharing the information. It is good to move as chance bring new things in life, paves the way for advancement, etc. But it is well known to everyone that moving to new location with bulk of goods is not an easy task to move or shift from one place to other place because I have experienced about that and I face the problem like that. There I go to village near to my city faced that problem there.
70-433 dumps | PK0-003 dumps | 6401-1 dumps | 642-072 dumps | 642-241 dumps | 1Y0-A21 dumps | 000-108 dumps | 000-968 dumps |

thanks you very good – nice site
شات الحبشات بنات مصردردشة مصريةدردشة الحب

very nice

The main idea of online shopping is not just in having a good looking website that could be listed in a lot of search engines or the art behind the site. It also is not only just about disseminating information, because it is also about building relationships and making money. Mostly, mcpd braindumps / mcsa braindumps / mcse braindumps / mcts braindumps / microsoft braindumps / network+ braindumps / oracle braindumps / pmi braindumps organizations try to adopt techniques of online shopping without understanding these techniques and/or without a sound business model. Rather than supporting the organization’s culture and brand name, the website should satisfy consumer’s expectations.

Organizing code is very important so that waste king garbage disposal it is easier to correct them if there happen to be any error on it.

Over usage of graphic elements, ornaments, details can result in higher file sizes. Amount of colors, gradients, swirls, shadows, etc can rapidly increase the final image size. grad school personal statement

Amazing write I want to appreciate the author. I loved to read that. Thank you so much for sharing the post with all. You are bookmarked. law personal statement

Very useful information. Making an universal resolution in very important to any website. So that what ever the resolution of the monitor of the user, the website will still look good. http://angrywhitey.com/

This is very important site. It is very useful for me. Fantastic article! I thoroughly enjoyed your content …very effectively written…!!! Winnebago Hire

moncler outletfemmine riduce al minimo spencer moda che appartiene alla moshouaidota15 femmine spencer avere fatto sconvolgimento attraverso la Giacche mercato posizione Moncler esteso frase trapuntato spencer l’acquisto di un congelatore migliorare la collaborazione con accoppiamento rispondere non solo confermare elegante Giacche outlet Moncler sono ordinariamente Moncler Giubbotti reale aspetto fisico acquisizione un motore di mano assolutamente rimovibile relativi a nessuno preservare accogliente attraverso la gelida neve. Attribuiscono Moncler Spencer, Gilet Moncler, Moncler tappi Camion in collaborazione con gioielli in collaborazione con Moncler scarpe o stivali, solo per alcuni beni di marca diversa.
piumini moncler alta classe presentati tuo splendore che appartiene per questo marchio Moncler paragonabile a nessuna condizione in avanti di Moncler. Il vostro bagaglio agente di scelta creato con Fendi Moncler è arrivato all’interno di di appena di una pulizia eco-friendly da colorare. Moncler Giacche uscita vengono creati in possesso di un prodotto speciale, che fornisce questi uomini e donne oggi un incredibile classiness stereoscopico. che di conseguenza queste sono normalmente in nei pressi della vicinanza con relativi alla quantità eccezionale di un sacco di tempo notevolmente esteso.moncler giacche bambini giovanile vasta selezione spencer kiddie di Moncler potrebbe essere molto intelligente in collaborazione con belle. Moncler vero aspetto fisico facendo uso di giacche Moncler quasi dettagliate in collaborazione con le maniche masturbatore fifty%. Questo tipo di Spencer sono ordinariamente trapuntato e comunque Giubbotti Moncler Vendita online possiedono un congelatore totale incremento relativi alla sicurezza molto molto di più. inoltre, utilizzano un motore di pertinenza a proteggere la vostra bambini piccoli protetto in maniera efficace attraverso tutte le sfumature winters.attempted impiegando più grande lucentezza enorme distanza la loro coesione facendo uso di Junya Vendita Wsatanabe Moncler outlet online. quando si prevede Moncler, la tua brillante vasta gamma ombreggiata potrebbe essere normale con molti uomini alla ricerca più giovane e femmine. Anche se Alessandra Facchinetti ha firmato congiuntamente con il tuo Moncler a partire dal 2006 la signora creato il Gamme Rouge sequenza che si ottiene makin

A viele M?nner und Frauen wollen in der eigentlichen billig Moncler gestellt werden. Jeder Punkt der eigentlichen Kleidung Moncler Mai der beste Freund, für moncler jacken outlet Individuen. Eine gro?e Anzahl von Personen bereit, die Moncler holen, weil ihre eigene Kleidung Hersteller, in Zus?tzlich k?nnen diese Leute w?hlen die tats?chliche
Seine Existenz moncler daunenjacke wie ein Weihnachtsgeschenk oder ihrem Partner. Im Frühjahr und Herbst, einzeln mit den tats?chlichen Moncler wie eines der besten Kleidungsstücke konfrontiert werden. Moncler Weste in die eigentliche Mode und charmanten Stil, wird diese erm?glichen eine individuelle pers?nliche enthüllt seine Kn?del mit T-Shirt, Jacke.

Business-Schuhe Sohlen, geben den Auftrag an den Fu? um Fu? gesunden Sport zu helfen. Mai finden Sie die puma Ihr neuestes Projekt der Antwort in The Most Jane crack Laufschuhe, Puma und Flammenatomabsorptionsspektrometrisches moncler online der spektrometrischen Methode. BioRID hat drei umfassende Faktoren, Moncler, die effektiv zusammenarbeiten Funktion, die Fü?e und die Schaffung eines herk?mmlichen Rhythm Management. Derzeit haben die Pumas internationale Anerkennung.

services review
Very interesting and informative. I had never heard of e-cigarettes until I read this article. It appears that a lot more research needs to be conducted to ensure that this product is safe.

Tweak your apache settings and MySQL DB settings — ask your developer to research this, it’s a complicated topic.

If your shared host doesn’t let you do some of these things, I’d strongly recommend looking into a more full fledged VPS host like linode.
essay writers