smarty课程---最最最简单的smarty例子
生活随笔
收集整理的這篇文章主要介紹了
smarty课程---最最最简单的smarty例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
smarty課程---最最最簡單的smarty例子
一、總結
一句話總結:其實所有的模板引擎的工作原理是差不多的,無非就是在php程序里面用正則匹配將模板里面的標簽替換為php代碼從而將兩者混合為一個php的混編文件,然后執行這個混編文件。
smarty的兩個主要函數:
assign->分配變量
display->加載模板
?
1、smarty的功能是什么?
用一個php文件給一個html文件分配變量
其實也是模板和控制器分離(也就是mvc模式)
?
2、smarty的兩個函數的主要作用是什么?
assign->分配變量
display->加載模板
替換模板中的變量,例如把{$name}替換為<? echo $this->arr['name'];?>
然后用include加載執行這個模板
?
3、我們在外部訪問的是哪個文件?
訪問的是index.php,而不是index.html,也就是相對于thinkphp里面的控制器,我們根本就沒有訪問模板,模板只是作為模板文件使用,編譯好后被扔到了控制器里面
也就是說,在thinkphp里面我們只訪問了控制器,而模板里面的內容是扔到了控制器里面,我們根本沒有訪問模板,我們一直都只是在控制器
?
4、display函數里面為什么不能用echo而用include?
直接echo的話php代碼不執行,因為echo本身就在php里面,所以不能接著套php標簽,而編譯好的模板里面是php代碼
include作用:不僅僅是引入,還執行
?
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代碼不執行,因為echo本身就在php里面,所以不能接著套php標簽 19 }?
?
?
二、最最最簡單的smarty例子
1、截圖
目錄結構
?
?
運行成功后的樣例
?
?
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代碼不執行,因為echo本身就在php里面,所以不能接著套php標簽 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>?
?
?
總結
以上是生活随笔為你收集整理的smarty课程---最最最简单的smarty例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: laravel 在nginx服务器上除了
- 下一篇: Springsecurity之Filte