PHP templating with str_replace?

2020-05-27 02:07发布

I think the basic principle of a PHP templating system is string replacing, right? So can I just use a string to hold my html template code like

$str_template = "<html><head><title>{the_title}</title><body>{the_content}</body></html>"

and in the following code simply do a str_replace to push the data into my template variable like

str_replace( $str_template, '{the_title}', $some_runtime_generated_title );
str_replace( $str_template, '{the_content}', $some_runtime_generated_content );

then at last

echo $str_template; 

Will this hopefully make the whole variable passing process a bit faster? I know this could be a weird question but has anybody tried it?

标签: php templates
9条回答
戒情不戒烟
2楼-- · 2020-05-27 02:36

If you do only variable expansion, you can do:

$str_template = "<html><head><title>$the_title</title><body>$the_content</body></html>";

It will work as well...
Several people wonder why there are template system when PHP is already a template system...

Of course, there are other advantages to these systems, like more secure access to variables, perhaps easier to handle by designers (or to generate by tools), limitation of logic in the view layer... Which is a common criticism of heavy template systems like Smarty, with so much logic that you can almost write another template system with it! ;-)

Some template systems, like Savant, takes a middle road. :-)

查看更多
闹够了就滚
3楼-- · 2020-05-27 02:37

Yes, that is the basic idea behind a templating system. You could further abstract it, let an other method add the brackets for example.

You could also use arrays with str_replace and thus do many more replaces with one function call like this

str_replace(array('{the_title}', '{the_content}'), array($title, $content), $str_template);

The system I work with is Spoon Library, their templating system is pretty rock solid, including compiled templates, which are a huge performance gain.

查看更多
The star\"
4楼-- · 2020-05-27 02:38

You simply can't make a template this way.
A real life template will require not only plain variables to fill but also several control structures, or at least some sort of blocks to control certain areas of the page (to make a loops for example).
So, you can't make a template with str_replace only. Some regexps and sophisticated parsing will be required too.

Thus, it's better to stick with a template engine which already at your disposal - a PHP itself!

查看更多
登录 后发表回答