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

PHP 輕量模板類 Lightpage_Template:變量替換 + 模板文件加載

     編輯:PHP 綜合知識

類代碼

<?php
class Lightpage_Template {
    public $header = null;
    public $footer = null;
    public $parsing = [];   // ['key' => 'value']
    public $template = 'list.html';
    public $toParse = null; // 模板內容緩存

    public function parse(): string {
        $search = []; $replace = [];

        if ($this->header !== null) {
            $search[] = '{header}'; $replace[] = $this->header;
        }
        if ($this->footer !== null) {
            $search[] = '{footer}'; $replace[] = $this->footer;
        }
        foreach ($this->parsing as $k => $v) {
            $search[] = '{'.$k.'}'; $replace[] = $v;
        }

        if ($this->toParse === null && $this->template !== null) {
            $path = ROOT . '/Templates/' . $this->template;
            $this->toParse = file_get_contents($path);
        }

        return str_replace($search, $replace, $this->toParse ?? '');
    }
}

使用範例

<?php
define('ROOT', __DIR__);
$tpl = new Lightpage_Template();
$tpl->header = '<header>站點頭部</header>';
$tpl->footer = '<footer>版權所有</footer>';
$tpl->parsing = ['title' => '文章列表', 'list' => '<ul>...</ul>'];
$tpl->template = 'article_list.html';
echo $tpl->parse();

模板文件 article_list.html

{header}
<h1>{title}</h1>
{list}
{footer}

局限與擴展方向

缺點改進
僅支援純文本替換,無邏輯判斷/循環引入 Smarty/Twig/Blade,或自行實現 {if}/{foreach} 解析器
無緩存機制,高併發下重複讀取文件編譯為 PHP 文件緩存,或 Redis 緩存編譯結果
無 XSS 保護,變量直接輸出輸出時自動 htmlspecialchars,或提供 {var|escape} 管道
無模板繼承/區塊實現 extends/block 機制

何時使用

  • 極簡項目、靜態頁生成、郵件模板、無框架環境快速原型。
  • 正式項目建議直接接入成熟模板引擎。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved