使用Smarty PHP模板构建移动站点

时间:2010-12-19 02:50:28

标签: php mobile smarty templating

我有一个使用smarty的自定义应用程序。我需要我的应用程序支持移动设备(iphone,driods等...)我知道一般网络看起来不错,而且在很多情况下我也可以使用CSS黑客攻击,但Smarty中是否有办法检测浏览器是什么正在使用然后根据该请求提供模板?

一种模板: - 台式机和笔记本电脑 另一个 - 智能手机

3 个答案:

答案 0 :(得分:1)

你可以在Smarty中使用普通的PHP:

{php}
if (preg_match('/iphone/i', $_SERVER['HTTP_USER_AGENT'])) {
   // iphone
} else if (preg_match('/android/i', $_SERVER['HTTP_USER_AGENT'])) {
   // android
} // and so on...
{/php}

或者,您可以创建一个Smarty插件。我记得它是这样的:

function smarty_function_useragent_match($params, $template) {
    return preg_match($params['pattern'], $_SERVER['HTTP_USER_AGENT']);
}

在Smarty网站上查找有关Writing plugins的更多信息。

答案 1 :(得分:0)

更好的方法是,根据用户代理/设备加载模板集,例如:

$template_dir = '/path/to/default/templates/';
if($mobile_device) {
    $template_dir = '/path/to/default/templates/';
}

或更像这样的动态:

$template_dir = '/path/to/templates/' . $device;

这里的$ device是多么精细,取决于应用程序的需求。

答案 2 :(得分:0)

在Smarty 3中不推荐使用普通PHP,不要使用它!

您可以使用库,例如​​Mobile DetectDetect Mobile Browsers

plugins目录function.detect_mobile.php中创建一个插件:     

function smarty_function_detect_mobile($params, &$smarty) {

require_once './libraries/Mobile_Detect.php';
$detect=new Mobile_Detect;

$smarty->assign('is_mobile', false);
if($detect->isMobile()) {
    $smarty->assign('is_mobile', true);
}
}

然后在模板文件中使用它:

{detect_mobile}
{if $is_mobile} 
<link rel="stylesheet" href="css/styles-mobile.css" type="text/css" />
{else}
<link rel="stylesheet" href="css/styles.css" type="text/css" /> 
{/if}
相关问题