哈,好久不寫blog了,今天就隨便寫點吧,怎么這blog的編輯器成了fck的了呢?
突發靈感,寫了一個非常簡單的模版類,雖然沒啥先進的東西,不過我總認為靈感也是需要積累的。
功到自然成嘛。模版類文件代碼:
<?php
/**
* 作者:darasion
* 版權:使用或轉載注明作者
*
*/
class darasiontemplate{
var $template = "";
var $var = array();
var $classname = "darasiontemplate";
/**
* 設定 參數/模版
*
*/
function setvar($name,$value){
if(strtolower(get_class($value))==strtolower($this->classname)){
$this->var[$name]=$value->parse();
}else{
$this->var[$name]=$value;
}
}
/**
* 獲得 參數/解析后的模版
*
*/
function getvar($name){
if(isset($this->var[$name])){
return $this->var[$name];
}
}
/**
* 設定模版路徑
*
*/
function settemplate($tpl){
$this->template = $tpl;
}
/**
* 輸出html
*
*/
function out(){
echo $this->parse();
}
/**
* 解析模版
*
*/
function parse(){
ob_start();
include_once($this->template);
echo $content=ob_get_contents();
ob_end_clean();
return $content;
}
}
?>
這個模版類能夠支持模版的嵌套,只要將子模版類的實例當作參數設置給父模版即可
使用方法:
test.php
<?php
include("darasiontemplate.php");
//建立父模版
$tpl=new darasiontemplate();
$tpl->settemplate("inc/__tpl.php");
//父模版參數
$tpl->setvar("title","參數title");
$tpl->setvar("a","參數a");
$tpl->setvar("b","參數b");
//建立子模版
$tpl1=new darasiontemplate();
$tpl1->settemplate("inc/__tpl1.php");
//設置子模版參數
$tpl1->setvar("kk","kk");
//將子模版放入父模版中
$tpl->setvar("c",$tpl1);
$tpl->out();
?>
//父模版:__tpl.php
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title><?php echo @$this->getvar("title");?></title>
</head>
<body>
<?php echo @$this->getvar("a");?>
<?php echo @$this->getvar("b");?>
<?php echo @$this->getvar("c");?>
</body>
</html>
//子模版:__tpl1.php
<table width="200" border="1" bordercolor="#000000">
<tr>
<td><?php echo @$this->getvar("kk");?></td>
<td><?php echo @$this->getvar("kk");?></td>
<td><?php echo @$this->getvar("kk");?></td>
</tr>
</table>
輸出的html:
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312">
<title>參數title</title>
</head>
<body>
參數a 參數b
<table width="200" border="1" bordercolor="#000000">
<tr>
<td>kk</td>
<td>kk</td>
<td>kk</td>
</tr>
</table>
</body>
</html>
在這個模版類中,使用了與其他模版類不同的方法來實現:
1、把其他模版類中的類似{a}的換成了<?php echo @$this->getvar("a");?>而且子模版和父模版中他們的形式相同。
2、如果需要循環,只需要寫php的循環代碼即可,如:foreach()。
這樣做的好處是:
1、省去了字符串的替換過程(一大堆的正則總是看不懂,呵呵,給自己想了個偷懶的辦法)。
2、省去了重新學習一大堆說是標簽還不是標簽的東西的過程(還是因為自己懶)。
3、更重要的好處是,用這個模版類對應的模版,是完全可以用dreamweaver等工具進行可視化編輯的。
由于是一時興起寫成的東西,肯定經不起仔細的推敲,只是給大家提出一個想法,供大家討論;如果真的能在實際中對你有所幫助,自然更好了。
新聞熱點
疑難解答