2010-07-03 135 views
2

我的朋友我就簡單的PHP模板引擎的工作這裏是一些代碼可以someboady幫我補充文件,包括功能 喜歡%include.sidebar.html%和循環功能,這樣我就可以運行循環或告訴我一些其他簡單的PHP模板引擎簡單的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> 

回答

4

你可以使用Smarty,但是PHP本身就是一個模板語言。爲什麼要更換它?

+2

有趣的閱讀:http://fabien.potencier.org/article/34/templating-engines-in-php和http://fabien.potencier.org/article/35/templating-engines-in-php-follow-向上 – igorw 2010-07-04 09:56:46

1

我用Smarty

+0

我downvoted,因爲你沒有花時間來解釋你的選擇決定,並展示如何這個答案(雖然我不明確什麼是真的被問)。做到這一點,我會審查我的投票。 – crafter 2016-10-14 08:53:40

0

雖然略少輕便,Twig是一個功能強大的模板引擎用極其簡單的語法。

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(); 
    } 
?> 

真的希望幫助。