使用 PHP 作为模板引擎并拥有精简模板

  • 本文关键字:拥有 引擎 PHP 使用 php
  • 更新时间 :
  • 英文 :


我根据以下建议使用 PHP 作为模板引擎:https://stackoverflow.com/a/17870094/2081511

我有:

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

在页面/到/模板上.php我有:

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

我正在尝试从模板页面中删除一些必需的语法,以使其他人更容易开发自己的模板。我想做的是保留 {$variable} 的变量命名约定,但从模板文件中删除这些行:

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

我正在考虑将它们放在包含语句的两侧,但随后它只会将该语句显示为文本而不是包含它。

好吧,如果你想要一个非常简单的模板解决方案,这可能会有所帮助

<?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>

最新更新