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

Kes*_*air 6 html php 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;
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*c B 12

file.html:

<html>

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

</html>
Run Code Online (Sandbox Code Playgroud)

file.php:

<?php
    $name = "Keshav";
    include('file.html');
?>
Run Code Online (Sandbox Code Playgroud)

不会比这更简单.是的,它使用全局变量,但如果简单是游戏的名称,就是这样.只需访问"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>
Run Code Online (Sandbox Code Playgroud)

  • 如果可以的话我会给+100,没有必要重新发明轮子.PHP意味着PHP超文本处理器,并且"超文本"不是错误的... (2认同)
  • 一百次是的.**PHP是模板引擎**.启用短标签,它不是一个半坏的模板引擎. (2认同)

ari*_*ayu 7

如果脚本更容易维护,那么将它们移动到函数中会怎么样?

这样的事情:

<?php

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

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

   return $template;
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

<?php

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

echo get_content($file, $data);
Run Code Online (Sandbox Code Playgroud)