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

Smarty 模板引擎變數輸出完整指南:設定、指派、顯示與修飾器

     編輯:PHP 相關知識

環境設定 (config.inc.php)

<?php
require_once 'libs/Smarty.class.php';
$smarty = new Smarty();

$smarty->setTemplateDir('./templates');
$smarty->setCompileDir('./templates_c');
$smarty->setCacheDir('./cache');
$smarty->setConfigDir('./configs');

$smarty->caching = false;          // 開發關閉快取
$smarty->left_delimiter  = '<{';
$smarty->right_delimiter = '}>'; // 避免與前端框架衝突
?>

PHP 端指派變數 (index.php)

<?php
require 'config.inc.php';

$title = 'PHP 測試標題';
$content = 'Smarty 練習!';

$newsList = [
    ['name' => 'PHP 程式測試', 'date' => '2015-08-01'],
    ['name' => 'PHP 影音教學', 'date' => '2015-08-02'],
    ['name' => 'Smarty 學習',   'date' => '2015-08-03'],
];

$tableHeader = ['標題', '姓名', '年齡'];

$smarty->assign('title', $title);
$smarty->assign('content', $content);
$smarty->assign('newsList', $newsList);      // 二維陣列
$smarty->assign('header', $tableHeader);     // 一維陣列

$smarty->display('index.tpl');
?>

模板檔 (templates/index.tpl)

<h1><{$title}></h1>
<p>測試內容:<{$content}></p>

<h3>表格測試</h3>
<table border="1">
  <tr><{foreach $header as $h}><th><{$h}></th><{/foreach}></tr>
  <{foreach $newsList as $row}>
  <tr>
    <td><{$row.name}></td>
    <td><{$row.date}></td>
  </tr>
  <{/foreach}>
</table>

常用修飾器 (Modifiers)

進階技巧

  • 區塊函數:<{foreach}>, <{section}>, <{if}> 控制流程
  • 模板繼承:<{extends file='layout.tpl'}> + <{block name='content'}>
  • 快取:$smarty->caching = true; $smarty->cache_lifetime = 3600;
  • 自訂函數/修飾器:$smarty->registerPlugin('modifier', 'my_modifier', 'my_func');

輸出結果預覽

測試標題:PHP 測試標題
測試內容:Smarty 練習!
表格測試:
標題 | 姓名 | 年齡
PHP 程式測試 | 2015-08-01
PHP 影音教學 | 2015-08-02
Smarty 學習  | 2015-08-03
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
修飾器說明範例
escapeHTML 轉義<{$var|escape}>
escape:"htmlall"全字元實體化<{$var|escape:'htmlall'}>
truncate:30:"..."截斷字串<{$longText|truncate:30:'...'}>
date_format:"%Y-%m-%d"日期格式化 (需 timestamp)<{$timestamp|date_format:'%Y-%m-%d'}>
upper/lower大小寫轉換<{$name|upper}>
default:"預設值"變數為空時顯示預設<{$var|default:'無資料'}>