php:简单的模板引擎

时间:2011-01-20 20:25:15

标签: php templates

我有一个名为load_template()

的函数

此函数有两个参数

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

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

模板中的

('test')我希望能够写

<?php echo $title; ?>

然后致电

load_template('test', array('title' => 'My Title'));

并填写它。

我该怎么做?

<小时/> 输出缓冲方法。 我已经提出了下面的代码 我相信它可以改进。

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;
}

2 个答案:

答案 0 :(得分:10)

function load_template($name, $vars)
{
  extract($vars);
  include $name;
}

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

答案 1 :(得分:2)

这样的东西?

function load_template($name, $vars)
{
  include('template/'.$name.'.tpl'); //.tpl, .inc, .php, whatever floats your boat
}

并且在template/whatever.tpl中你有:

...
<title><?php echo $vars['title'] ?></title>
...

...
<?php if (!empty($vars['content'])): //template still needs to know if the content is empty to display the div ?>
    <div id="content">
<?php echo $vars['content']; ?>
    </div>
<?php endif; ?>
...

当然,这假设输出是直接打印的。 您可以直接打印tpl文件,或生成字符串,或缓冲tpl文件的输出并从load_template返回