So we all know that you should always, not only in PHP, separate code from content/design/html. (I have seen people that say the opposite here today)
I mean, you don’t want one of these in bigger projects, do you?
<?php
echo '<div id="blah"><b>'
. $username . '</b>'
. $stuff . '<more HTML mixed with PHP...>';
?>
But: What is a good approach to separate code from content?
I have been using a simple template system that replaces wildcards in templates mostly.
e.g:
<div id="blah"><b>%USERNAME%</b>%STUFF% <...>
(located in a single file)
Later you can just call a function similar to GetTemplate( 'myTemplate', array ( 'USERNAME' => 'Stranger' ) );
Finally, the questions:
- Is this a good way of separating code and content?
- How do you do that when not working with a framework?
- Is there a better way?
Im not fan ov additional templating languages (that replace wildcards) instead i like to keep my templates pure php so my vertion of what you have done would be:
<div id="blah"><b><?php echo $username ?></b><?php echo $stuff ?><...>echo GetTemplate( 'myTemplate.php', array ( 'username' => 'Stranger', 'stuff' => 'Stuff' ) );I alos combine this with helper functions/object->methods as well for example:
<?php echo link_to($name, $url); ?>I generally apply helpers like these to commonly used tags/structures as well as having a general purpose html tag one that looks something like
content_tag($tag, $content, $attributes);This helps me avoid a php echo for tons of attributes for random tags. I obviously dont use it for every html tag i use only for ones where it makes for better readability than a ton of echos.As far as templating engines go i dont really see the benefit as php is templating language. As far as non-programmers/coders they have to leanr the syntax for a loop and a variable any how so i dont see how changing it to wildcards or the {} syntax of smarty adds anything.