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?
Sure, you need to have the arguments in the right order though.
str_replace()
Also might be a good idea to put the templates in their own file instead of keeping them in a string. Then just read them via
file_get_contents()
or similar.Actually the answer from "Your Common Sense" is the right one. You could use PHP to use the current context and replace variables. Instead of writing the output, you could do ob_start() to hold it in a buffer and get the replaced content. Easy and elegant!
I would build a parser that breaks the code into it’s tokens (variables and plain text). As an easy approach, you could use the
pre_split
function to do this:Now you can iterate the tokens and check whether it is a variable or plain text:
The advantage of this approach is that variables are not replaced in text that has already been replaced. So:
Here the text would be replaced by
Lorem bar {bar} sit amet …
and notLorem bar bar sit amet …
as it would happen with your code, when{bar}
is being replaced after{foo}
.basically the idea is that one, but template are something that offers lot more, for example RainTPL is WYSIWYG, because it replace relative paths into the template with the server paths, in this way you design your template in local and it works on the server without needs to change img/css.
That is generally the basic idea for a templating system. Real templating systems have many more capabilities, but at the core this is what they do.
You ask whether this will "make the whole variable passing process a bit faster". Faster than what? Are you running into performance problems with something you're doing right now?
It's a good Idea to use a template engine.
But your idea gets slow when the html is larger and get slower if you are need more variables. remember the replace is executed for every request.
you can use html files containing php tags for output (like
<?=$var?>
) and loops only. include them via "include" to your php code. thats much faster.take a look at smarty. this is my favorite template engine for php. smarty has many good features like caching and it is extendable by plugins.
if you understand german take a look here. there is a small introduction into smarty.