寫了乙個簡單實用的PHP模板引擎

2021-05-28 17:01:44 字數 1609 閱讀 6743

php模板引擎很多,但要麼很龐大,要麼效率很低,如果只是要實現php**與程式分離,就只要乙個簡單的模板引擎就行了。今天抽空寫了乙個。

xt.class.php

<?php

/** created on 2011-10-08

* @author xyl

* this is ****** template engine for your site

*/class xt

}function setdata($k,$v)

function subtemplate($filename)

}else }

function __parsedata($content)

}if(!empty($this->subtp))

}$content = preg_replace("//iu", "<?php include('$this->t_cache/\\1.php');?>", $content);

//變數

$content = preg_replace("/\/s", "<?=\\1?>", $content);

//邏輯

$content = preg_replace("//iu", "<?php if(\\1) ?>", $content);

//迴圈

$content = preg_replace("//iu", "<?php foreach(\\1) ?>", $content);

return $content;}

function parse($filename=null,$sub=false)

!$sub?$this->content_path=$content_path:'';

}function out() }

?>

用法:test.php

<?php

/** created on 2011-9-29

** to change the template for this generated file go to

* window - preferences - phpeclipse - php - code templates

*/include("xt.class.php");

$title="測試";

$content="內容";

$footer="底部";

$arr=array("a","b");

$xt=new xt();

//通過setdata方法賦值給模板

$xt->setdata('title',$title);

$xt->setdata('content',$content);

$xt->setdata('arr',$arr);

$xt->setdata('chk',true);

//除錯模板開啟,正式用時關閉,預設是關閉的

$xt->compile=true;

//編譯模板,模板檔案預設與當前頁面同名,如當前檔案為test.php,模板檔案則對應於template/test.html

$xt->parse();

//輸出內容

$xt->out();

?>

test.html

乙個簡單的模板類(PHP)

接上話,有了乙個資料操作類,這樣專案只能簡單地運算元據,但是要達到能夠和美工一起顯示美好的頁面,則需要乙個比較好的模板引擎。與smarty這樣比較龐大的模板引擎相比,我想下面這個則真算得小得多了。這個模板類是我以前在網上看到的,寫得比較好,所以我就引用了,還不知道作者是誰,這裡就先講一下這個類的原理...

乙個簡單的模板類(PHP)

有了乙個資料操作類,這樣專案只能簡單地運算元據,但是要達到能夠和美工一起顯示美好的頁面,則需要乙個比較好的模板引擎。與smarty這樣比較龐大的模板引擎相比,我想下面這個則真算得小得多了。這個模板類是我以前在網上看到的,寫得比較好,所以我就引用了,還不知道作者是誰,這裡就先講一下這個類的原理。首先,...

簡單的寫了乙個列印Lua Table的函式

簡單的寫了乙個將lua table 列印成json的格式,當然這個函式還是有點bug的,就是不能區分 同時存在陣列和key vlaue,如 local test 會被當做陣列處理,由於專案中沒有匯入json庫,不能使用json.encode 所以自己隨便了乙個,基本上滿足需求,後面也就沒有管了,如果...