smarty课程---最最最简单的smarty例子
生活随笔
收集整理的這篇文章主要介紹了
smarty课程---最最最简单的smarty例子
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
smarty課程---最最最簡(jiǎn)單的smarty例子
一、總結(jié)
一句話總結(jié):其實(shí)所有的模板引擎的工作原理是差不多的,無(wú)非就是在php程序里面用正則匹配將模板里面的標(biāo)簽替換為php代碼從而將兩者混合為一個(gè)php的混編文件,然后執(zhí)行這個(gè)混編文件。
smarty的兩個(gè)主要函數(shù):
assign->分配變量
display->加載模板
?
1、smarty的功能是什么?
用一個(gè)php文件給一個(gè)html文件分配變量
其實(shí)也是模板和控制器分離(也就是mvc模式)
?
2、smarty的兩個(gè)函數(shù)的主要作用是什么?
assign->分配變量
display->加載模板
替換模板中的變量,例如把{$name}替換為<? echo $this->arr['name'];?>
然后用include加載執(zhí)行這個(gè)模板
?
3、我們?cè)谕獠吭L問(wèn)的是哪個(gè)文件?
訪問(wèn)的是index.php,而不是index.html,也就是相對(duì)于thinkphp里面的控制器,我們根本就沒(méi)有訪問(wèn)模板,模板只是作為模板文件使用,編譯好后被扔到了控制器里面
也就是說(shuō),在thinkphp里面我們只訪問(wèn)了控制器,而模板里面的內(nèi)容是扔到了控制器里面,我們根本沒(méi)有訪問(wèn)模板,我們一直都只是在控制器
?
4、display函數(shù)里面為什么不能用echo而用include?
直接echo的話php代碼不執(zhí)行,因?yàn)閑cho本身就在php里面,所以不能接著套php標(biāo)簽,而編譯好的模板里面是php代碼
include作用:不僅僅是引入,還執(zhí)行
?
9 function display($file){ 10 $str=file_get_contents($file); 11 $ptn='/\{\$(.+)\}/i'; 12 $rep='<?php echo $this->arr["$1"];?>'; 13 $rst=preg_replace($ptn, $rep, $str); 14 $dstfile="templates_c/".md5($file).".php"; 15 file_put_contents($dstfile, $rst); 16 include($dstfile); 17 //echo "$str"; 18 //直接echo的話php代碼不執(zhí)行,因?yàn)閑cho本身就在php里面,所以不能接著套php標(biāo)簽 19 }?
?
?
二、最最最簡(jiǎn)單的smarty例子
1、截圖
目錄結(jié)構(gòu)
?
?
運(yùn)行成功后的樣例
?
?
2、代碼
?
index.php
1 <?php 2 include("libs/Smarty.class.php"); 3 4 $s=new Smarty(); 5 $s->assign("name","user1"); 6 $s->assign("age","30"); 7 8 $s->display("templates/index.html"); 9 ?>?
模板 index.html
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <h1>{$name}</h1> 9 <h1>{$age}</h1> 10 </body> 11 </html>?
Smarty.class.php
1 <?php 2 class Smarty{ 3 public $arr; 4 5 function assign($key,$val){ 6 $this->arr[$key]=$val; 7 } 8 9 function display($file){ 10 $str=file_get_contents($file); 11 $ptn='/\{\$(.+)\}/i'; 12 $rep='<?php echo $this->arr["$1"];?>'; 13 $rst=preg_replace($ptn, $rep, $str); 14 $dstfile="templates_c/".md5($file).".php"; 15 file_put_contents($dstfile, $rst); 16 include($dstfile); 17 //echo "$str"; 18 //直接echo的話php代碼不執(zhí)行,因?yàn)閑cho本身就在php里面,所以不能接著套php標(biāo)簽 19 } 20 } 21 ?>?
Smarty編譯后的:fb5aa1cd1261d08d02db6f7dc314d9ab.php
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 </head> 7 <body> 8 <h1><?php echo $this->arr["name"];?></h1> 9 <h1><?php echo $this->arr["age"];?></h1> 10 </body> 11 </html>?
?
?
總結(jié)
以上是生活随笔為你收集整理的smarty课程---最最最简单的smarty例子的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: laravel 在nginx服务器上除了
- 下一篇: Springsecurity之Filte