PHP 正在用 HTML 注释在 php 语句中回复 The < & >



我目前正在尝试为我正在处理的项目创建一个小型模板引擎,并且我正在使用一个系统,我正在用预设标签替换{$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;
} else {
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 文件中重新声明 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
}

相关内容

最新更新