网站支持多套前台模板(主题/皮肤),用户可切换、后台可指定、或按域名/设备自动选择。核心思路:模板文件同名、目录隔离,运行时动态设置 template_dir。
project/
├── templates/
│ ├── default/ # 默认主题
│ │ ├── index.tpl
│ │ ├── header.tpl
│ │ └── footer.tpl
│ ├── blue/ # 蓝色主题
│ │ ├── index.tpl
│ │ ├── header.tpl
│ │ └── footer.tpl
│ └── mobile/ # 移动端主题
│ ├── index.tpl
│ └── ...
├── templates_c/ # 编译目录(按主题自动分子目录)
└── index.php
<?php
require_once __DIR__ . '/libs/Smarty.class.php';
$smarty = new Smarty();
$smarty->compile_dir = __DIR__ . '/templates_c';
$smarty->config_dir = __DIR__ . '/configs';
// 1. 确定当前主题
$availableThemes = ['default', 'blue', 'mobile'];
$defaultTheme = 'default';
// 优先级:URL参数 > Session > Cookie > 默认
$theme = $defaultTheme;
if (isset($_GET['theme']) && in_array($_GET['theme'], $availableThemes)) {
$theme = $_GET['theme'];
$_SESSION['theme'] = $theme; // 持久化
} elseif (isset($_SESSION['theme']) && in_array($_SESSION['theme'], $availableThemes)) {
$theme = $_SESSION['theme'];
} elseif (isset($_COOKIE['theme']) && in_array($_COOKIE['theme'], $availableThemes)) {
$theme = $_COOKIE['theme'];
}
// 2. 设置模板目录
$smarty->template_dir = __DIR__ . "/templates/$theme";
// 3. 通用变量赋值
$smarty->assign([
'site_name' => 'MySite',
'current_theme' => $theme,
'themes' => $availableThemes,
'theme_switcher_url' => '?theme=', // 切换链接前缀
]);
// 4. 显示模板
$smarty->display('index.tpl');
<html>
<head><title>{$site_name} - Default</title></head>
<body style="background:#fff; color:#333">
<h1>欢迎来到 {$site_name} (默认主题)</h1>
{include file='theme_switcher.tpl'}
<hr>{$content}</body></html>
<html>
<head><title>{$site_name} - Blue</title></head>
<body style="background:#e0f0ff; color:#003366">
<h1>欢迎来到 {$site_name} (蓝色主题)</h1>
{include file='theme_switcher.tpl'}
<hr>{$content}</body></html>
<div class="theme-switcher">
切换主题:
{foreach $themes as $t}
<a href="{$theme_switcher_url}{$t}" style="margin:0 5px; {if $t==$current_theme}font-weight:bold{/if}">
{$t}
</a>
{/foreach}
</div>
<?php
function detectMobile(): bool {
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
$mobileKeywords = ['Mobile', 'Android', 'iPhone', 'iPad', 'Windows Phone'];
foreach ($mobileKeywords as $kw) {
if (stripos($ua, $kw) !== false) return true;
}
return false;
}
// 在确定主题逻辑前插入
if (!isset($_GET['theme']) && !isset($_SESSION['theme'])) {
if (detectMobile() && in_array('mobile', $availableThemes)) {
$theme = 'mobile';
}
}
Smarty 会自动在 compile_dir 下按 template_dir 路径哈希创建子目录,不同主题编译文件互不干扰,无需手动配置。
in_array($theme, $availableThemes) 防止目录遍历攻击if (!$smarty->templateExists('index.tpl')) $theme = $defaultTheme;templates_c/ 需 Web 服务器写权限<?php
// 子主题仅覆盖 header.tpl,其余落回父主题
$themeDirs = [
__DIR__ . "/templates/$theme", // 子主题优先
__DIR__ . "/templates/$parentTheme", // 父主题兜底
];
$smarty->template_dir = $themeDirs; // Smarty 3+ 支持数组目录,按顺序查找
此方案已在多个电商、CMS 项目生产环境稳定运行,支持数十套主题热切换。