smarty模板引擎中自定義函數(shù)的方法
更新時間:2015年01月22日 15:36:14 投稿:shichen2014
這篇文章主要介紹了smarty模板引擎中自定義函數(shù)的方法,實例分析了自定義函數(shù)的定義、注冊及調用技巧,需要的朋友可以參考下
本文實例講述了smarty 自定義函數(shù)方法,分享給大家供大家參考。具體如下:
本實例目的:輸出 times 次 con的內容(輸出4次hello world)
文件1:
復制代碼 代碼如下:
<?php
//創(chuàng)建smarty對象
require_once("./libs/Smarty.class.php");
$smarty = new Smarty();
//自定義一個函數(shù)
//說明:(1)、$arr為一個數(shù)組;(2)、tpl調用形式{test times="4" size="5" con="hello,world" color="red"}
function test($arr){
$str = "";
for($i=0;$i<$arr['times'];$i++){
$str .= "<font size='".$arr['size']."' color='".$arr['color']."'>".$arr['con']."</font>";
}
return $str;
}
//注冊函數(shù) registerPlugin
$smarty->registerPlugin("function","test","test");//第二個參數(shù)是模板文件調用的函數(shù)名稱,可變;第三個參數(shù)是上面自定義的函數(shù)名稱;相應于一個對應關系
//創(chuàng)建smarty對象
require_once("./libs/Smarty.class.php");
$smarty = new Smarty();
//自定義一個函數(shù)
//說明:(1)、$arr為一個數(shù)組;(2)、tpl調用形式{test times="4" size="5" con="hello,world" color="red"}
function test($arr){
$str = "";
for($i=0;$i<$arr['times'];$i++){
$str .= "<font size='".$arr['size']."' color='".$arr['color']."'>".$arr['con']."</font>";
}
return $str;
}
//注冊函數(shù) registerPlugin
$smarty->registerPlugin("function","test","test");//第二個參數(shù)是模板文件調用的函數(shù)名稱,可變;第三個參數(shù)是上面自定義的函數(shù)名稱;相應于一個對應關系
$smarty->display("temp.tpl");
?>
模板文件:temp.tpl
復制代碼 代碼如下:
<html>
<h2>smarty自定義函數(shù)的使用</h2>
{test times="3" con="hello world" size="3" color="green"}
</html>
<h2>smarty自定義函數(shù)的使用</h2>
{test times="3" con="hello world" size="3" color="green"}
</html>
注意:smarty 3.1.8 已經不支持注冊函數(shù) register_function,應換成 registerPlugin
希望本文所述對大家的php程序設計有所幫助。
您可能感興趣的文章:
相關文章
Django中datetime的處理方法(strftime/strptime)
這篇文章主要介紹了Django中datetime的處理方式(strftime/strptime),本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07
PHPStudy hosts文件可能不存在或被阻止打開及同步hosts失敗問題
這篇文章主要介紹了PHPStudy hosts文件可能不存在或被阻止打開,同步hosts失敗,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05
CodeIgniter實現(xiàn)更改view文件夾路徑的方法
這篇文章主要介紹了CodeIgniter實現(xiàn)更改view文件夾路徑的方法,需要的朋友可以參考下2014-07-07

