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

4

我有一个使用Smarty的定制应用程序。我需要我的应用程序支持移动设备(iPhone,Droid等...)。我知道一般的网页看起来还不错,并且在许多情况下我可以使用CSS技巧,但是在Smarty中是否有一种方法来检测正在使用的浏览器,然后根据该请求提供模板?

一种类型的模板适用于: -台式机和笔记本电脑 另一种适用于 -智能手机

3个回答

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网站上查找有关编写插件的更多信息。


0

在Smarty 3中,纯PHP已经被弃用,请不要使用它!

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

Create a plugin in plugins directory, 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);
}
}

Then use it in the template file:

{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}


0
更好的方法是根据用户代理/设备加载模板集,例如:
$template_dir = '/path/to/default/templates/';
if($mobile_device) {
    $template_dir = '/path/to/default/templates/';
}

或者更加动态地像这样:

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

设备的粒度取决于应用需求。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接