2017-04-05 60 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>