我根据这个建议使用PHP作为模板引擎:https://stackoverflow.com/a/17870094/2081511
我有:
$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;
?>
我正在尝试从模板页面中删除一些必需的语法,以便其他人更容易开发自己的模板。我想要做的是保留{$ variable}的变量命名约定,但从模板文件中删除这些行:
<?php
echo <<<EOF
EOF;
?>
我正在考虑将它们放在include语句的任何一侧,但是它只会将该语句显示为文本而不是包含它。
答案 0 :(得分: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>