Want to get Lullabot article, videocast, and podcast announcements delivered right to your in-box? Let us know your email address (we won't share it) and we'll let you know when anything exciting happens.

Theming based on http headers

While working on the new MTV UK website, I ran into a rather strange problem. The theme on the MTV UK site is fairly complex, especially the main menu, since whatever menu item is current is taken out of context and placed elsewhere on the page. To do this, you look at what menu item is active in Drupal and extract it from the array.

But what do you do when you get a 404 "page not found"? How can you change your theme (e.g., the menu layout) based on this fact? A failsafe or default case would generally work, but in the case of MTV UK, their theme and requirements were too complex for a simple default. What we need is a way to intercept this 404 before it is shown so we can adjust our theme appropriately.

Impossible? Not hardly. But it's not intuitive either. Here's the scoop on the 2 lines of code needed for this trick:

<?php
  $headers
= drupal_set_header();
 
  if (
strstr($headers, 'HTTP/1.0 404 Not Found')) {
?>

Place that anywhere in your theme, and voila, you can alter your theme based on the fact the page isn't found. That would make it really easy to essentially change out your template in that case.

Works equally well for any type of header.

Happy theming!

Comments on this post will automatically be closed three months from the original post date.

Comments

Just talked with chx on IRC,

Just talked with chx on IRC, he mentioned I should have used strpos() instead of strstr(). Performance boost, it's faster to return a boolean then a string. Thanks Karoly!

thx for tip

thx for tips :) its a great idea, well done!

greets and happy new year