首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

Smarty 配置文件實戰:集中管理版面常數、多區塊載入與作用域控制

     編輯:PHP 綜合知識

前言

Smarty 配置文件 (.conf) 專為「版面常數」設計:顏色、寬度、文字標籤等。設計師可直接修改配置文件,無需動到 PHP 或模板邏輯。本文示範目錄結構、配置文件語法、config_load 多區塊載入、作用域控制與實戰範例。

目錄結構

project/
├── configs/           # 配置文件目錄 (config_dir)
│   └── view.conf
├── libs/
│   └── Smarty.class.php
├── tpl/               # 模板目錄 (template_dir)
│   └── index.tpl
├── com/               # 編譯目錄 (compile_dir)
└── index.php          # 入口

初始化設定 (init.inc.php)

define('ROOT_PATH', dirname(__FILE__));
require ROOT_PATH . '/libs/Smarty.class.php';

$tpl = new Smarty();
$tpl->template_dir = ROOT_PATH . '/tpl/';
$tpl->compile_dir  = ROOT_PATH . '/com/';
$tpl->config_dir   = ROOT_PATH . '/configs/';  // 關鍵:指定配置文件目錄
$tpl->left_delimiter  = '<{';
$tpl->right_delimiter = '}>';

配置文件語法 (configs/view.conf)

# 全域變數 (無區塊)
border = 2
tabWidth = 600
bgColor = #FFFF00
align = center

[theme1]        # 區塊:主題 1
colSpan = 4
title = "主題一標題"
btnColor = #FF6600

[theme2]        # 區塊:主題 2
colSpan = 3
title = "主題二標題"
btnColor = #0099CC

模板中載入與使用 (index.tpl)

{* 載入全域 + theme1 區塊,作用域 global 讓所有子模板可用 *}
{config_load file="view.conf" section="theme1" scope="global"}

{#title#}

內容區塊,按鈕顏色:{#btnColor#}
{* 另一種存取方式 *} {$smarty.config.border} {$smarty.config.tabWidth}

控制器 (index.php)

require 'init.inc.php';
$tpl->display('index.tpl');

作用域詳解

scope 值生效範圍適用場景
local (預設)僅當前模板頁面專用配置
parent當前模板 + 父模板 (include 它的模板)佈局模板共享
global所有模板 (含後續 include)全站通用常數 (站名、版權、主色調)

進階:動態切換主題

// 根據用戶偏好或域名決定 section
$theme = $_COOKIE['theme'] ?? 'theme1';
$tpl->assign('activeTheme', $theme);
{config_load file="view.conf" section=$activeTheme scope="global"}

最佳實踐建議

  1. 命名規範:全域用小寫底線 site_name,區塊用 PascalCase [HeaderStyle]。
  2. 類型提示:雖然配置文件皆為字串,但在模板用 {$var|intval} 或 {$var|escape:'html'} 防呆。
  3. 版本控管:將 configs/ 納入 Git,設計師修改可直接 PR。
  4. 快取:配置文件變更需清除 Smarty 快取 ($tpl->clear_cache()) 或設定 force_compile = true 開發模式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved