2017-04-05 197 views
0

我使用PHP按照這個建議模板引擎:https://stackoverflow.com/a/17870094/2081511使用PHP作爲模板引擎和具有薄模板

我:

$title = 'My Title'; 
ob_start(); 
include('page/to/template.php'); 
$page = ob_get_clean(); 

和頁面/以/上的template.php我有:

<?php 
echo <<<EOF 
<!doctype html> 
<html> 
<title>{$title}</title> 
... 
EOF; 
?> 

我試圖從模板頁面中刪除一些必需的語法,以使其他人更容易開發自己的模板。我想這樣做是保留{$變量}變量命名約定,但請從模板文件中的這些行:

<?php 
echo <<<EOF 
EOF; 
?> 

我想這會讓他們在包括陳述的任何一方,但隨後只是將該聲明顯示爲文本而不是包含它。

+1

我不知道,如果你想要做什麼是可能的,用<?= $ title取代{$ title}; ?>,但會增加更多標記並增加複雜性。您是否查看了模板系統,如小鬍子/句柄,它們對最終用戶有一個簡單的語法{{title}},它不熟悉php – bumperbox

+0

「page/to/template.php」是否回顯了某些內容?你在用'$ page'做什麼? – PHPglue

+0

PHP中的'@ bumperbox''{$ title}'裏面的雙引號或heredocs,實際上毫無意義。 '{}'適用於諸如'{$ obj-> title}'或'{$ singleDimensionalArray [$ number]}'的情況。 – PHPglue

回答

0

好吧,如果你想有一個非常簡單的模板解決方案,這可能幫助

<?php 


$title = 'My Title'; 

// Instead of including, we fetch the contents of the template file. 
$contents = file_get_contents('template.php'); 

// Clone it, as we'll work on it. 
$compiled = $contents; 

// We want to pluck out all the variable names and discard the braces 
preg_match_all('/{\$(\w+)}/', $contents, $matches); 

// Loop through all the matches and see if there is a variable set with that name. If so, simply replace the match with the variable value. 
foreach ($matches[0] as $index => $tag) { 
    if (isset(${$matches[1][$index]})) { 
    $compiled = str_replace($tag, ${$matches[1][$index]}, $compiled); 
    } 
} 

echo $compiled; 

模板文件應該是這樣的

<html> <body> {$title} </body> </html>