简单的PHP模板引擎

时间:2010-07-03 05:23:07

标签: php templates

我的朋友我正在研究简单的php模板引擎这里是一些代码可以帮助我添加文件包括功能 像%include.sidebar.html%和循环函数,所以我可以运行循环或告诉我一些其他简单的PHP模板引擎

<?

class Template {

private $template, $vars;


public function SetTemplete($tempname) {
    $templatePathAndName  = $tempname;
    if(file_exists($templatePathAndName))
        $this->template = file_get_contents($templatePathAndName);
    else
        die("Template not found... aborting...");
}

public function setVar($var, $content) {
    $this->vars[$var] = $content;
}


public function replaceAll() {
  foreach($this->vars as $var => $content) {
    $this->template = str_replace("{" . strtoupper($var). "}", $content, $this->template);
  }
}

public function publish() {
    $this->replaceAll();
    echo $this->template;
}

public function includeFile(){
  foreach($this->vars as $var => $content) {
    $this->template = str_replace("<-" . strtoupper($var). "->", 
                                  file_get_contents($content), 
                                  $this->template);
  }
}

$tpl = new Template;
$tpl->SetTemplete(base_path."home.html");
$tpl->setVar("SITE_NAME", "Simple Template Class2");
$tpl->publish();

?>
///home.html 
<html>
    <head>

    </head>
    <body>
        {SITE_NAME}
    </body>
</html>

5 个答案:

答案 0 :(得分:4)

你可以使用Smarty,但php本身就是一种模板语言。为什么要更换它?

答案 1 :(得分:1)

TinyButStrong是相当不错但仍然很小的引擎。

答案 2 :(得分:1)

我使用Smarty

答案 3 :(得分:0)

虽然轻微一点轻量级,Twig是一个功能强大的模板引擎,语法非常简单。

答案 4 :(得分:0)

想法,并没有真正为您的班级格式化:

<?php
    $glob1 = glob("templates/$template/*");
    for($1=0;$i<=count($glob1)-1;$i++) {
        $file = $glob1[$i];
        $file = str_replace('templates/', '', $file);
        $template = str_replace('%include.$file%', (include("templates/$file")), $template();
    }
?>

真的希望有所帮助。