smarty的原理:php
<?php class Smarty { $ldelimiter = "{";//左分隔符 $rdelimiter = "}";//友分隔符 $attr = array();//用來存貯變量的數組 //向模板裏面註冊變量 function assign($key,$value) { $this->attr[$key] = $value; } //顯示模板的方法 function display($url) { //1.獲取靜態模板的內容 $str = file_get_contents($url); //2.根據正則匹配str裏面出現的全部{}裏面的內容 //{$a} -> <?php echo $attr[$a] ?> //3.將替換好的頁面保存臨時文件 touch(".test.php"); file_put_contents(); //4.將臨時文件拿到當前頁面顯示 include(".test.php"); } }
訪問的是PHP文件,其中路徑就按照訪問的PHP文件來定。可是顯示的是html。html
test.php數組
test.php <?php include("../init.inc.php"); //註冊變量 $smarty->assign("name","張三"); $smarty->assign("arr",array(1,2,3,4,5)); $smarty->assign("test","my name is zhangsan"); $smarty->assign("title",啊啊啊啊啊啊); //顯示模板 $smarty->display("test.html");
test.html函數
<html> <head></head> <body> <{$name}> <{$arr.one}> <{config_load file='test.conf'} section='one'> <div style="width:20px;height:20px;background-color:<{#color#}>"></div> <{$smarty.now|date_format:%Y-%m-%d %H:%M:%S}> <{$test|truncate:5}>//截取字符串
<{date name ="riqi" value="2017-2-3" time=true}>
<{color name="color"}>
<{textarea name="txt" toolbar="full" color="red"}>
<{/textarea}>//塊函數要有首和尾
<{cishu num=3}>
<{font da=50}>
電話卡會打架
<{/font}>
</body> </html> $smarty.const.XXX 取常量 $smarty.config.color 和 #color#同樣
test.confthis
[one] color=red [two] color=green
自定義變量調節器modifier.keyword.phpurl
<?php function smarty_modifier_keyword($str,$key) { return str_replace($key,"<mark>{$key}</mark>",$str); }
自定義函數function.cishu.phpspa
//num參數表明輸出次數 function smarty_function_cishu($args,$smarty) { $num = $args["num"]; $str = ""; for($i=0;$i<$num;$i++) { $str = $str."<div style='width:100px;height:100px;background-color:green'></div>"; } return $str; }
自定義塊函數block.font.php3d
<?php function smarty_block_font($args,$content,$smarty,$a) { if(!$a)//走頭的時候沒有內容,走尾的時候把內容改變 { $da = $args["da"]; return "<span style='font-size:{$da}px'>{$content}</span>"; } }
顯示結果code