2

I currently am using page-front.tpl.php to display my Blog content type in a View. I want to use a different template if the user is on a mobile device, and have them either redirected to the mobile view, or have the Drupal theme layer use a different template.

2 Answers 2

2

To do this you need to setup some method that will detect whether the use is coming from a mobile device and than add a function in your template.php file to switch to your mobile template.

For the mobile detection, there are a number of modules available for this but for this specific use case, I would recommend Mobile Switch because it provides a specific variable you can use for testing in your theme (others like Mobile Tools might as well, this is just one I've used before). From documentation:

Development with Mobile Switch.

The module provides four system variables:

1. mobile_switch_ismobiledevice
2. mobile_switch_istablet
3. mobile_switch_ismobiletheme
4. theme_mobile

From here, you just need to add a template suggestion to your theme through the preprocess_page function using this variable, ex:

function YOURTHEME_preprocess_page(&$variables) {

  global $mobile_switch_ismobiledevice;

  if ((request_path() == 'YOUR_PATH') && $mobile_switch_ismobiledevice) {
    $variables['template_file'] = 'mobile-YOURTEMPLATE';
  }

}

This method assumes you want to specifically switch between two template files, if you would prefer to use a separate mobile theme, than the Mobile Switch or Mobile Tools module have configuration options to help you do this.

1
  • Note for Drupal 7: use $variables['theme_hook_suggestions'][] = 'page__YOURTEMPLATE';
    – mwallisch
    Mar 15, 2014 at 10:21
1

You should be able to use a combination of Browscap and Mobile Switch.

Browscap

Browscap provides an improved version of PHP's get_browser() function.

The get_browser() function can be used to tell what a visitor's browser is capable of [...]

Mobile Switch

The Mobile Switch module provides a simple automatic theme switch functionality for mobile devices, detected by Browscap or Mobile Detect.

If you're looking to do it through code (e.g. you would prefer to put something in your existing tpl.php) then Browscap provides a handy browscap_get_browser() function which is a kind of replacement for the PHP function get_browser(), so you could do something like the following (pseudo-code):

$browser = browscap_get_browser();

if ($browser == "MOBILE_BROWSER") {
 print $MY_MOBILE_VIEW;
}
else {
 print $MY_DESKTOP_VIEW;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.