CodeIgniter 3如何根据数据库值动态加载对应模板布局
动态模板加载实现方案
1. 读取数据库模板配置
先从general_settings表获取当前选中的模板值,示例代码(PDO):
$db = new PDO('mysql:host=localhost;dbname=你的数据库名', '用户名', '密码'); $stmt = $db->query("SELECT template FROM general_settings LIMIT 1"); $currentLayout = $stmt->fetchColumn() ?: 'layout01'; // 默认 fallback 到 layout01
2. 动态加载样式资源
根据获取到的$currentLayout,拼接静态资源路径引入:
<link rel="stylesheet" href="assets/frontend/<?php echo $currentLayout; ?>/style.css">
3. 动态引入视图组件
用include/require加载对应目录下的_header.php、_footer.php及页面文件:
// 加载头部组件 $headerPath = "views/frontend/{$currentLayout}/_header.php"; if (file_exists($headerPath)) { include $headerPath; } else { // 加载默认头部作为兜底 include "views/frontend/layout01/_header.php"; } // 加载当前页面内容 include "views/frontend/{$currentLayout}/index.php"; // 加载尾部组件 $footerPath = "views/frontend/{$currentLayout}/_footer.php"; if (file_exists($footerPath)) { include $footerPath; } else { include "views/frontend/layout01/_footer.php"; }
4. 前台模板切换提交逻辑
前台下拉框代码
<form method="post"> <select name="template"> <option value="layout01" <?php echo $currentLayout === 'layout01' ? 'selected' : ''; ?>>布局1</option> <option value="layout02" <?php echo $currentLayout === 'layout02' ? 'selected' : ''; ?>>布局2</option> <option value="layout03" <?php echo $currentLayout === 'layout03' ? 'selected' : ''; ?>>布局3</option> </select> <button type="submit">切换布局</button> </form>
后台处理提交
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['template'])) { $selectedLayout = $_POST['template']; // 校验合法模板,避免恶意输入 $allowedLayouts = ['layout01', 'layout02', 'layout03']; if (in_array($selectedLayout, $allowedLayouts)) { $stmt = $db->prepare("UPDATE general_settings SET template = ?"); $stmt->execute([$selectedLayout]); // 刷新页面生效 header("Location: {$_SERVER['PHP_SELF']}"); exit; } }
5. 优化建议
- 定义常量统一管理路径,方便维护:
define('FRONTEND_TEMPLATE_ROOT', 'views/frontend/'); define('FRONTEND_ASSETS_ROOT', 'assets/frontend/');
- 加入Session缓存,减少数据库查询次数:
session_start(); if (!isset($_SESSION['current_layout'])) { $_SESSION['current_layout'] = $currentLayout; } else { $currentLayout = $_SESSION['current_layout']; } // 切换模板时同步更新Session if (isset($_POST['template']) && in_array($_POST['template'], $allowedLayouts)) { $_SESSION['current_layout'] = $_POST['template']; }
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

