对模板引擎使用 preg_replace()
Using preg_replace() for template engines
当我尝试学习基本的模板引擎时,我尝试了不同的代码。我注意到这个我不明白的问题。
我是新手,如有任何帮助,我们将不胜感激。
Template.php :
class Template {
public function render ($template_name) {
$path = $template_name . '.php';
if (file_exists($path)) {
$contents = file_get_contents($path);
$contents = preg_replace('/\{\% for (.+) = (\d+) to (\d+) \%\}/', '<?php for ($ = ; $ < ; $++): ?>', $contents);
$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $; ?>', $contents);
$contents = preg_replace('/\{\% endfor \%\}/', '<?php endfor ?>', $contents);
eval(' ?>' . $contents . '<?php ');
}else{
exit ('<h1> Template Eror</h1>');
}
}
}
?>
test.php :
{% for i = 0 to 10 %}
<b> i = {% i %} </b><br>
{% endfor %}
index.php :
include 'Template.php';
$template = new Template;
$template->render('myTemplate');
输出是:
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
但是在 Template.php 中,如果 $contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $; ?>', $contents);
放在 'for' 'endfor' 行之前,输出显示:
This page isn’t working
127.0.0.1 is currently unable to handle this request.
HTTP ERROR 500
第二行:
$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $; ?>', $contents);
替换每个 {% endfor %}
所以第三行永远不会匹配任何 {% endfor %}
这就是为什么你必须交换这两行。
当我尝试学习基本的模板引擎时,我尝试了不同的代码。我注意到这个我不明白的问题。 我是新手,如有任何帮助,我们将不胜感激。
Template.php :
class Template {
public function render ($template_name) {
$path = $template_name . '.php';
if (file_exists($path)) {
$contents = file_get_contents($path);
$contents = preg_replace('/\{\% for (.+) = (\d+) to (\d+) \%\}/', '<?php for ($ = ; $ < ; $++): ?>', $contents);
$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $; ?>', $contents);
$contents = preg_replace('/\{\% endfor \%\}/', '<?php endfor ?>', $contents);
eval(' ?>' . $contents . '<?php ');
}else{
exit ('<h1> Template Eror</h1>');
}
}
}
?>
test.php :
{% for i = 0 to 10 %}
<b> i = {% i %} </b><br>
{% endfor %}
index.php :
include 'Template.php';
$template = new Template;
$template->render('myTemplate');
输出是:
i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
但是在 Template.php 中,如果 $contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $; ?>', $contents);
放在 'for' 'endfor' 行之前,输出显示:
This page isn’t working
127.0.0.1 is currently unable to handle this request.
HTTP ERROR 500
第二行:
$contents = preg_replace('/\{\% (.+) \%\}/', '<?php echo $; ?>', $contents);
替换每个 {% endfor %}
所以第三行永远不会匹配任何 {% endfor %}
这就是为什么你必须交换这两行。