萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

Smarty 多模板切换实现:动态加载不同主题/皮肤模板文件

需求场景

网站支持多套前台模板(主题/皮肤),用户可切换、后台可指定、或按域名/设备自动选择。核心思路:模板文件同名、目录隔离,运行时动态设置 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');

模板文件示例

templates/default/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>

templates/blue/index.tpl

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

公共切换组件 templates/default/theme_switcher.tpl(所有主题共用)

<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 项目生产环境稳定运行,支持数十套主题热切换。

copyright © 萬盛學電腦網 all rights reserved