PHP在带有HTML注释的php语句中替换

问题描述 投票:0回答:1

我目前正在尝试为我正在研究的项目创建一个小型模板引擎,并且我正在使用一个系统,在该系统中我将{$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 html template-engine
1个回答
0
投票

您无需在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;
}

然后上面的代码应返回世界,代替{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
}
© www.soinside.com 2019 - 2024. All rights reserved.