php:简单的模板引擎

Hai*_*ood 4 php templates

我有一个叫做的函数 load_template()

这个函数有两个参数

  • $ name =>模板的名称
  • $ vars =>数组键=>要在模板中替换的值变量.

我想要这个工作的方式是.

在模板('test')中我希望能够写

<?php echo $title; ?>
Run Code Online (Sandbox Code Playgroud)

然后打电话

load_template('test', array('title' => 'My Title'));
Run Code Online (Sandbox Code Playgroud)

并填写它.

我怎样才能做到这一点?


输出缓冲方法. 我已经提出了下面的代码.
我相信它可以改进.

public static function template($name, $vars = array()) {
  if (is_file(TEMPLATE_DIR . $name . '.php')) {
    ob_start();
    extract($vars);
    require(TEMPLATE_DIR . $name . '.php');
    $contents = ob_get_contents();
    ob_end_clean();
    return $contents;
  }
  throw new exception('Could not load template file \'' . $name . '\'');
  return false;
}
Run Code Online (Sandbox Code Playgroud)

Osw*_*ald 10

function load_template($name, $vars)
{
  extract($vars);
  include $name;
}
Run Code Online (Sandbox Code Playgroud)

如果要捕获变量中的输出,请使用ob_startob_get_clean进行换行.