Build iPhone Compatible Drupal Websites Using iWebkit: Part 2
on
Build iPhone Compatible Drupal Websites Using iWebkit: Part 2
An important part of bulding mobile websites is automatic detection of the user-agent (mobile device) so you can switch to an appropriate theme, or re-configure the layout for your mobile browsing. Once you've detected the device, you can present the website in a theme tailored to it.
This second post in my series of tutorials on mobile themes for Drupal focuses on how to implement automatic user-agent detection and switch your base theme to a mobile theme.

In Drupal there are many options/modules availabe to detect the user agent and switch themes. At its most basic, the necessary code for this could be implemented using hook_init() as follows:
mymodule_init() {
if(isset("$_HTTP_HOST")) {
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'iphone') || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'ipod')) {
global $conf;
$conf['theme_default'] = 'my_mobile_theme';
}
}
}This code could be for detecting any user-agent and setting global $conf['theme_default'] variable to your mobile theme.
Some modules which implement similar functionality include:
- Mobile Tools is a very advanced module targeted both towards making a mobile version of your existing Drupal site, and detecting user agents for switching theme to mobile theme. A good tutorial how to use this module is available here.
- WURLF is module provides an API for to detect which device is accessing the site and also determine the device's capabilities (e.g. screen size, support for ajax, which device, touch_screen, etc ...). WURLF is available for download from SourceForge (it's an opensource project).
- Browsercap is a module based upon the Browser Capabilities Project
- iDrupal module also provides similar functionality to Browsercap but that is only limited to iPhones and iTouch.
hook_init will be incompatible with some forms of caching. I'm thinking mainly of Boost. However you can do the same with a combination of few rules in .htaccess with a unique URL for the mobile site. You can also mix in some cookies to have the user permanently choose which site they prefer.













Just wondering when the next part of this excellent tutorial will come out. Great reading so far!