I'm writing a simple templating layer in PHP but I've got myself a little stuck. Here's how it works at the moment:
Firstly I use fetch_template
to load the template contents from the database - this works (and I collect all the templates at startup if you're interested).
I use PHP variables in my template code and in the logic - e.g.:
// PHP:
$name = 'Ross';
// Tpl:
<p>Hello, my name is $name.</p>
I then use output_template
(below) to parse through the variables in the template and replace them. Previously I was using template tags with a glorified str_replace
template class but it was too inefficient.
/**
* Returns a template after evaluating it
* @param string $template Template contents
* @return string Template output
*/
function output_template($template) {
eval('return "' . $template . '";');
}
My problem, if you haven't already guessed, is that the variables are not declared inside the function - therefore the function can't parse them in $template
unless I put them in the global scope - which I'm not sure I want to do. That or have an array of variables as a parameter in the function (which sounds even more tedious but possible).
Does anyone have any solutions other than using the code from the function (it is only a one-liner) in my code, rather than using the function?
Thanks, Ross
P.s. I know about Smarty and the vast range of templating engines out there - I'm not looking to use them so please don't suggest them. Thanks!