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

Smarty 模板引擎實戰筆記:配置、語法與常用技巧總整理

     編輯:PHP 相關知識

Smarty 基本配置

<?php
include_once(IncludeFile . '/libs/Smarty.class.php');
$tpl = new Smarty();
$tpl->caching = false;           // 關閉快取
$tpl->compile_check = true;      // 檢查模板更新
$tpl->template_dir = IncludeFile . '/templates/' . Isite_tpl . '/';
$tpl->compile_dir  = IncludeFile . '/templates_c/';
$tpl->config_dir   = IncludeFile . '/configs/';
$tpl->cache_dir    = IncludeFile . '/cache/';
$tpl->left_delimiter  = '<{';
$tpl->right_delimiter = '}>';
?>

常用模板語法範例

迴圈與條件判斷

<{foreach key=key item=MMSPAN from=$TSortUrl}>
    <td align="left" valign="bottom" height="25">
    <{if $mysort eq $key}>
        <img src="images/sort_<{$key}>_1.gif" height="25" border="0" />
    <{else}>
        <a href="<{$MMSPAN}>"><img src="images/sort_<{$key}>.gif" height="25" border="0" /></a>
    <{/if}>
    </td>
<{/foreach}>

動態內容建議用 JS 載入

如使用者登入資訊,建議透過 JavaScript 非同步載入,避免快取導致顯示異常。

進階技巧

  • 子模板傳參:<{include file="SiteAllTop.html" mysort="0"}>
  • 取得 GET 參數:<{if $MMSPAN[0] eq $smarty.get.s}>selected<{/if}>
  • 移除 HTML 標籤:<{$OReDetail[6]|strip_tags}>
  • 註解語法:{* Smarty 註解 *}
  • 截取字串:{$foo|truncate:"`$fooTruncCount/$barTruncFactor-1`"}
  • 日期格式化:{$smarty.now|date_format:"%Y-%m-%d"}
  • 正則替換:{$articleTitle|regex_replace:"/[\r\t\n]/":" "}
  • 日期比較:<{if $smarty.now|date_format:"%Y-%m-%d" eq $MMSPAN[4]|date_format:"%Y-%m-%d"}><img src="images/newh.gif" /><{/if}>

實用方法

  • template_exists($f):檢查模板是否存在。
  • fetch():取得已指派模板的輸出內容,適合產生靜態頁面。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved