I'm trying to write a very basic template engine for a project and ended up taking the approach described in this article, which write template variables like [@variable]
and to simply use str_replace()
to parse the templates and put in the variable values.
This is really simply and seems to work well, but despite my best efforts there are situations in which basic logic is really needed in the template itself. I don't need anything complicated, just a way to have single if/else or ternary statements. For example, something like [if@something?"text":"other text"]
.
What might be a good approach to parsing basic logic in templates, like shown in the above example?
UPDATE:
I'm working on an AJAX heavy website, so I have a PHP AJAX controller that receives requests and then returns a JSON encoded response. Here's an example:
AJAX handler.php:
...
else if($req == 'getContent')
{
$template = new Template('template.tpl');
$template->setData(array(
'date' => time(),
'var' => 'foo',
'foo' => 'bar'
));
$response = array(
'error' => null,
'content' => template->getOutput()
);
}
...
echo json_encode($response);
template.tpl:
lots and lots and lots of HTML
........
variables [@date] mixed in [@foo] somewhere with HTML [@bar]
........
lots and lots and lots of HTML
If I wasn't using a template engine (which just uses str_replace()
to put the variable values into the template after getting it with file_get_contents()
), then I would have to do this:
AJAX handler.php:
...
else if($req == 'getContent')
{
$output = '
lots and lots and lots of HTML' . time() . '
........
variables ' . $foo . ' mixed in ' . $bar . 'somewhere with HTML
........
lots and lots and lots of HTML
';
$response = array(
'error' => null,
'content' => $output
);
}
...
echo json_encode($response);
The whole point of what I'm trying to accomplish here is to separate huge blocks of HTML text (in some cases, literally entire page bodies) from my AJAX handler and instead keep them in separate files, which is far more readable and keeps the AJAX handler from becoming ridiculously massive.