如何制作一个php模板引擎?

时间:2011-04-04 15:34:29

标签: php html arrays templates

我需要制作一个小而简单的php模板引擎,我搜索了很多,其中很多都太复杂而无法理解,我不想使用smarty和其他类似引擎,我从Stack Overflow中得到了一些想法这个:

$template = file_get_contents('file.html');
$array = array('var1' => 'value',
                'txt' => 'text');

foreach($array as $key => $value)
{
  $template = str_replace('{'.$key.'}', $value, $template);
}

echo $template;

现在而不是回显模板我只想添加包含“file.html”,它将显示具有正确变量值的文件,我想将引擎放在一个单独的位置,只是将它包含在模板中我的内容想要使用它声明数组,最后包括像phpbb这样的html文件。对不起,我要求的很多,但任何人都可以解释一下这背后的基本概念吗?

编辑:好吧,让我坦率地说我正在制作一个论坛脚本,我有很多想法,但我想让它的模板系统像phpbb所以我需要一个单独的模板引擎自定义一个,如果你可以帮助那么请你受邀与我合作。抱歉广告..:p

4 个答案:

答案 0 :(得分:11)

file.html:

<html>

<body>
<h3>Hi there, <?php echo $name ?></h3>
</body>

</html>

file.php:

<?php
    $name = "Keshav";
    include('file.html');
?>

不会比这更简单。是的,它使用全局变量,但如果简单是游戏的名称,就是这样。只需访问“http://example.com/file.php”即可离开。

现在,如果您希望用户在浏览器的地址栏中看到“file.html”,您必须将您的网络服务器配置为将.html文件视为PHP脚本,这有点复杂,但绝对可行。完成后,您可以将两个文件合并为一个文件:

file.html:

<?php
    $name = "Keshav";
?>
<html>

<body>
<h3>Hi there, <?php echo $name ?></h3>
</body>

</html>

答案 1 :(得分:5)

如果脚本更易于维护,您可以将它们移动到函数中吗?

类似的东西:

<?php

function get_content($file, $data)
{
   $template = file_get_contents($file);

   foreach($data as $key => $value)
   {
     $template = str_replace('{'.$key.'}', $value, $template);
   }

   return $template;
}

你可以这样使用它:

<?php

$file = '/path/to/your/file.php';
$data = = array('var1' => 'value',
                'txt' => 'text');

echo get_content($file, $data);

答案 2 :(得分:3)

一旦你解决了所有错误,解决了你自己陷入的巨大性能问题,你最终会得到模板引擎,就像Smarty和otheres一样。

这样的find'nplaceplace方法比编译PHP要慢得多。它不能很好地处理转义(你会遇到XSS问题)。添加条件和循环将非常困难,您迟早会需要它们。

答案 3 :(得分:1)

    <?php
    class view {
        private $file;
        private $vars = array();

        public function __construct($file) {
            $this->file = $file;
        }

        public function __set($key, $val) {
            $this->vars[$key] = $val;
        }

        public function __get($key, $val) {
            return (isset($this->vars[$key])) ? $this->vars[$key] : null;
        }

        public function render() {
            //start output buffering (so we can return the content)
            ob_start();
            //bring all variables into "local" variables using "variable variable names"
            foreach($this->vars as $k => $v) {
                $$k = $v;
            }

            //include view
            include($this->file);

            $str = ob_get_contents();//get teh entire view.
            ob_end_clean();//stop output buffering
            return $str;
        }
    }

以下是如何使用它:

    <?php
    $view = new view('userprofile.php');
    $view->name = 'Afflicto';
    $view->bio = "I'm a geek.";
    echo $view->render();
相关问题