總結:
$smarty的工作流程:
1:把需要顯示的全局變量,賦值,塞到對象內部的屬性上,一個數組內
2:編譯模版,把{$標籤},解析成響應的phpe echo代碼
3:引入編譯後的Php文件
使用smarty的步驟:
1:smarty是一個類,要使用,需先引入並實例化
2:assign賦值
3:dispaly[編譯到輸出]
smarty之辦
1:編譯模版,浪費時間
2:要把變量再重新賦值到對象屬性上,增大開銷
include('./mini.class.php');
$mini=new mini();
$mini->template_dir='./templates';
$mini->compile_dir='./compile';
$content='mao';
$mini->assign('content',$content);
$mini->display('03.html');
模版類:
<?php
/*
模版類的第一步:
把標籤解析Php輸出語句
模版文件-》PHP文件
*/
/*
爲了目錄清晰,我們把模版和編譯後的結果,放在不同的目錄裏
用2個屬性來記錄這2個目錄
*/
class mini
{
public $template_dir='';//模板文件愛你所在的位置
public $compile_dir='';//木板編譯後存放的位置
/*
string $template模版名
作用:調用compile來編譯模版,並自動引入
*/
//定義一個數組,用來接收外部的變量
public $_tpl_var=array();
public function assign($key,$value)
{
$this->_tpl_var[$key]=$value;
}
public function display($template)
{
$comp=$this->compile($template);
include($comp);
}
/*
string $template 模板文件名
return string
流程:把指定的模版內容讀過來,再編譯成php
*/
public function compile($template)
{ //讀出模版內容
$temp=$this->template_dir.'/'.$template;
$source=file_get_contents($temp);
$comp=$this->compile_dir.'/'.$template.'.php';
// 判斷模版是否已經存在
if(file_exists($comp)&&filemtime($temp)<filemtime($comp))
{
return $comp;
}
//替換模版內容
$source=str_replace('{$','<?php echo $this->_tpl_var[\'', $source);
$source=str_replace('}','\'];?>', $source);
// echo $source;
//再把編譯後的內容保存成點Php文件
file_put_contents($comp,$source);
return $comp;
}
}