I have an HTLP template file called "template.tmpl". In the template I have a few placeholders like {{NAME}}
and {{USERNAME}}
. I am then loading the template file into a variable called $template using file_get_contents
. I then put the $template
variable through a function which deals with replacing a series of placeholders.
My code is below and seems to be working fine, but wanted some input if there was any way to improve or make it more efficient.
function replace_tags($string){
$vars = array('{{NAME}}'=>'Bob', '{{USERNAME}}'=>'user_name', '<?'=>'', '?>'=>'');
return str_replace(array_keys($vars), $vars, $string);
}
$template = file_get_contents('template.tmpl', true);
echo replace_tags($template);
-
\$\begingroup\$ Please post real code that you use, not example code. If you build a template that you always use with "Bob" and "user_name", why did you bother making the template? \$\endgroup\$Pimgd– Pimgd2015年02月12日 10:17:41 +00:00Commented Feb 12, 2015 at 10:17
-
\$\begingroup\$ I havent finished the full thing yet, this is the start to building a template parsing script. \$\endgroup\$Ahmed– Ahmed2015年02月12日 10:30:09 +00:00Commented Feb 12, 2015 at 10:30
-
\$\begingroup\$ I think you should hold off on asking this question until you're a bit further along with the process. Right now there's not much we can do - keep in mind that most of the time, code reviews are about improving the code without changing the output. \$\endgroup\$Pimgd– Pimgd2015年02月12日 10:34:00 +00:00Commented Feb 12, 2015 at 10:34
-
\$\begingroup\$ For example, replace_tags could end like it is now, cleaning items from a template. It could also end up as a massive function which needs 30 arguments to put in place of placeholders. You'll get very different reviews on questions like those... I think you'll get answers that help you more if you have a bit more functionality to show. It will also help in determining what the eventual goal is with what you're trying to create. \$\endgroup\$Pimgd– Pimgd2015年02月12日 10:35:51 +00:00Commented Feb 12, 2015 at 10:35
1 Answer 1
I would say suggest writing your input like so:
function replace_tags($template, $placeholders){
$placeholders = array_merge($placeholders, array('<?'=>'', '?>'=>''));
return str_replace(array_keys($placeholders), $placeholders, $template);
}
$vars = array('{{NAME}}'=>'Bob', '{{USERNAME}}'=>'user_name');
$template = file_get_contents('template.tmpl', true);
echo replace_tags($template, $vars);
So that you can define the constant changes, and the changes you want to build depending on user, etc.