我认为 PHP 模板系统的基本原理是字符串替换,对吗? 那么我可以只使用一个字符串来保存我的 html 模板代码吗
$str_template = "<html><head><title>{the_title}</title><body>{the_content}</body></html>"
在下面的代码中,只需执行 str_replace 即可将数据推送到我的模板变量中,例如
str_replace( $str_template, '{the_title}', $some_runtime_generated_title );
str_replace( $str_template, '{the_content}', $some_runtime_generated_content );
最后
echo $str_template;
这是否有望使整个变量传递过程更快一些?我知道这可能是一个奇怪的问题,但有人试过吗?
最佳答案
是的,这是模板系统背后的基本思想。您可以进一步抽象它,例如让其他方法添加括号。
您还可以将数组与 str_replace 一起使用,从而用这样的一个函数调用进行更多替换
str_replace(array('{the_title}', '{the_content}'), array($title, $content), $str_template);
我使用的系统是 Spoon Library ,他们的模板系统非常坚固,包括编译模板,这是一个巨大的性能提升。
关于使用 str_replace 的 PHP 模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/477398/