0

Is it possible to serve up a specific page template based on browser version? If I can satisfy my IE 7 requirements with a special template, I'd prefer that rather than loading a bunch of extra css only used when IE7 is being used.

I have a special drop-down menu and though on its own will work in IE7, once it's a block and assigned to a region, issues start with height. I can put it in another region within a page template but then I'm changing all the css for all other browsers so I'd just as soon as have a template for the specific pages.

thanks

2

Normally that would be done with conditional css e.g. conditional_styles and that approach is recommended first.

Mainly because why change the entire template when only the CSS needs changing?

However, if you really need separate tpls ( e.g for new HTML markup ), you could probably use template suggestions in hook_preprocess_page after checking the browser user agent.

Something like this in template.php

/**
 * Implements hook_preprocess_page
 */
THEMENAME_preprocess_page(&$variables){
  // Requires browscap.ini, check PHP docs for details, else use $_SERVER['HTTP_USER_AGENT']
  $browser = get_browser();
  if($browser->browser == 'IE' && $browser->majorver == 7) {
    $variables['template_files'][] = 'page-ie7';
  }
}

After clearing all caches, you could then use page-ie7.tpl.php for IE7.

See the note on http://php.net/manual/en/function.get-browser.php for info else use $_SERVER['HTTP_USER_AGENT'] to check browser from request. You'll also need to make sure your cache varies on user agent as well.

  • 1
    Just be careful, if you do this with anonymous users and cache pages, you may/will serve up the wrong page, eg, an anonymous user using one browser visits a page, and it gets cached. then another anonymous user using a different browser visits the same page before the cache expires and gets that first user's version of the page. – Jimajamma May 15 '13 at 23:32
  • Yes, that's a possible issue and also why I wrote to make sure the cache varies on user agent as well. Personally, I'd just use conditional CSS. – David Thomas May 15 '13 at 23:51
  • Changing tpl files on browser versions is an easy way to get banned from search engines. Big companies don't like when what you feed their bot is different from what you serve your user (or the bot disguised as an user to test you). – Mołot May 16 '13 at 6:44
  • Thanks to all... I ended up just putting a simple menu item in the actual page.tpl.php and styling via css...and, gulp I'll admit it, star hacks for IE7 which is far better than any of the other potential problems! – kelly johnson May 16 '13 at 14:45

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.