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

自製輕量級 Smarty 模板引擎 MinSmarty:核心原理與使用範例

     編輯:PHP 相關知識

自製輕量級 Smarty 模板引擎 MinSmarty:核心原理與使用範例

為什麼需要模板引擎?

Smarty 等模板引擎核心價值在於分離邏輯與表現:PHP 程式師專注業務邏輯,前端工程師專注頁面設計,雙方互不干擾,團隊協作效率大幅提升。

MinSmarty 核心代碼(約 50 行)

<?php
class MinSmarty {
    var $template_dir = "./templates/";   // 模板目錄
    var $compile_dir  = "./templates_c/"; // 編譯快取目錄
    var $tpl_vars = [];                   // 變數容器

    // 指派變數
    function assign($tpl_var, $var = NULL) {
        if ($tpl_var !== NULL) $this->tpl_vars[$tpl_var] = $var;
    }

    // 顯示模板
    function display($tpl_file) {
        $tpl_path    = $this->template_dir . $tpl_file;
        $compile_path = $this->compile_dir . "com_" . $tpl_file . ".php";

        if (!file_exists($tpl_path)) return false;

        // 僅當模板更新或快取不存在時重新編譯
        if (!file_exists($compile_path) || filemtime($tpl_path) > filemtime($compile_path)) {
            $content = file_get_contents($tpl_path);
            // 將 {$var} 替換為 tpl_vars['var']; ?>
            $pattern = '/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i';
            $replace = '<?php echo $this->tpl_vars["${1}"];?>';
            $new_content = preg_replace($pattern, $replace, $content);
            file_put_contents($compile_path, $new_content);
        }
        include_once($compile_path);
    }
}
?>

使用範例

intro.php(控制器)

<?php
include_once("MinSmarty.class.php");
$title   = "這裡是標題";
$content = "這裡是內容 111111";
$tpl = new MinSmarty();
$tpl->assign("title", $title);
$tpl->assign("content", $content);
$tpl->display("intro.tpl");
?>

intro.tpl(模板)

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{$title}</title>
</head>
<body>
{$content}
</body>
</html>

運作流程

  1. assign() 將變數存入 $tpl_vars 陣列。
  2. display() 讀取 .tpl,用正則將 {$var} 編譯為 PHP 輸出語句,產生 com_intro.tpl.php 快取檔。
  3. 若模板未變更,直接 include_once 快取檔,跳過正則解析,效能極佳。
  4. 快取檔內容範例:<title><?php echo $this->tpl_vars["title"];?></title>

線上工具推薦

延伸閱讀:Smarty 入門教程、PHP 模板技術總結、PDO 資料庫技巧、PHP 運算符、網絡編程、基礎語法、OOP 入門、字串用法、MySQL 入門、常見資料庫操作匯總。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved