我目前正在尝试为我正在开发的项目创建一个小型模板引擎,并且我正在使用一个系统,用预设标签替换
{$tag}
。假设我将 {username}
放入模板文件中,它将返回一个字符串,即用户名。现在我想要超越仅仅用一个简单的字符串替换一个字符串。所以使用我输入的相同代码
$tpl->replace('getID', '<?php echo "test"; ?>);
它不起作用,所以当我去检查元素时,我看到它返回了
<!--? echo "test"; ?-->
...
所以现在我只是想弄清楚为什么它返回注释代码。
这是我的班级文件:
class template {
private $tags = [];
private $template;
public function getFile($file) {
if (file_exists($file)) {
$file = file_get_contents($file);
return $file;
}
return false;
}
public function __construct($templateFile) {
$this->template = $this->getFile($templateFile);
if (!$this->template) return "Error! Can't load the template file $templateFile";
}
public function set($tag, $value) {
$this->tags[$tag] = $value;
}
private function replaceTags() {
foreach ($this->tags as $tag => $value) {
$this->template = str_replace('{'.$tag.'}', $value, $this->template);
}
return true;
}
public function render() {
$this->replaceTags();
print($this->template);
}
}
我的索引文件是:
require_once 'system/class.template.php';
$tpl = new template('templates/default/main.php');
$tpl->set('username', 'Alexander');
$tpl->set('location', 'Toronto');
$tpl->set('day', 'Today');
$tpl->set('getID', '<?php echo "test"; ?>');
$tpl->render();
我的模板文件是:
<!DOCTYPE html>
<html>
<head></head>
<body>
{getID}
<div>
<span>User Name: {username}</span>
<span>Location: {location}</span>
<span>Day: {day}</span>
</div>
</body>
</html>
当我制作上述模板引擎时,我的目标之一是创建一些能够同时获取原始 php 和纯文本并能够输出可以正常工作的输出的东西(类似于 twig )。
我实际上想问的是如何获取被
<?php //... ?>
包围的 php 代码,并将其输出作为要在 html 中呈现的字符串进行管道传输。我现在要做的是使用 eval 语句。这基本上会将 $tpl->replace('getID', '<?php echo "test"; ?>);
变成 $tpl->replace('getID', eval('<?php echo "test"; ?>));
,这样就可以了。这是一种更优雅的方法,因为它允许在执行期间输入任何静态 php,并在解析后以纯文本(或 html)输出输出。
另一个解决方案,正如 Unbranded Manchester 所提到的,我可以使用专门的函数来完成评估代码的工作,而不是编写更多的 php 并直接将其输入。所以这个例子看起来像
$tpl->replace('getID', fetchID());
不必要时,您在 php 文件中重新声明 PHP。也就是说,您正在尝试打印
<?php
,这就是它混乱的原因。
所以,你可以替换这个:
$tpl->set('getID', '<?php echo "test"; ?>');
有了这个
$tpl->set('getID', 'test');
但是,您显然已经知道,您只是想走得更远,做到这一点的方法是在集合中使用 php 。所以,作为一个想法,你可以尝试这个:
$tpl->set('getID', testfunction());
(你在这里调用
testfunction
来定义这里的'getID'
)
所以,现在你想编写一个小函数来做一些奇特的事情,对于这个例子:
function testfunction(){
$a = 'hello';
$b = 'world';
$c = $a . ' ' . $b;
return $c;
}
上面的代码应该返回 hello world 来代替 {getID}
参考您的评论 - 如果您想更进一步并开始更深入地了解返回结果,您可以执行以下操作:
function testfunction(){
$content = "";
foreach ($a as $b){
ob_start();
?>
<span><?php echo $b->something; ?></span>
<a href="#">Some link</a>
<div>Some other html</div>
<?php
$content += ob_get_clean();
}
return $content
}