When I write PHP code for websites, I don’t like mixing business logic with the presentation layer and as such I tend to create markup templates. I’ve written a very lightweight template engine to facilitate this, since I really don’t want to move to a fully-fledged template framework like Smarty.
Here’s a simplified example of what I do:
function renderTemplatePage($page, $params)
{
$page = readTemplateFile("templates/{$page}");
$tokens = getTemplateTokens($page);
foreach($tokens as $token)
{
if(substr($token, 0, 6) == "%_TPL_")
{
$subPage = renderTemplatePage(tokenToPageName($token), $params);
$page = str_replace($token, $subPage, $page);
}
else
{
$page = str_replace($token, $params[$token], $page);
}
}
return $page;
}
Sample page:
<html>
<head><title>%_PageTitle_%</title></head>
<body>
<div id="header">%_TPL_Header_%</div>
<div id="content">%_TPL_Homepage_%</div>
<div id="footer">%_TPL_Footer_%</div>
</body>
</html>
A call to renderTemplatePage("index", array("PageTitle" => "Home")) would produce a page entitled “Home”, with content from the Header, Homepage and Footer templates.
I do all of my logic (including db queries, etc) before calling the rendering, so I can mass up a large $params array and just do a single call to render it all.
Are there any flaws in this methodology? Is there a more standard way to do this?
Its flawed. How do you handle template specific logic . Just out of curiosity how would you handle
ifsorloops