Smarty is an excellent template system used for PHP. It’s definitely the best and most versatile one I’ve seen.
Let’s say you have an index.tpl (the default template file extension in Smarty) with the following in it:
<html>
<head>
<title>Information</title>
</head>
<body>
Number 1: {$num1}<br>
Number 2: {$num2}<br>
</body>
</html>Now, to actually use the template you would have code like the following:
$smarty = new Smarty; $smarty->assign('num1', '111'); $smarty->assign('num2', '222'); $smarty->display('index.tpl');
As simple as that!
The output would be:
<html> <head> <title>Information</title> </head> <body> Number 1: 111<br> Number 2: 222<br> </body> </html>
That is just a simple example, and there are a lot more advanced things you can do with it. Check out the Smarty Crash Course for some ideas.
Before I knew about Smarty, I developed me own way of having HTML templates for the projects I developed. Admittedly, I still use it even though Smarty is so much more powerful. When I don’t need the versatility of Smarty, I just use my own method.
I started off by having a template directory with HTML files in it. These files consist of all the HTML code I want, and has placeholders to where content will be.
<html> <body> <div>%header%</div> <div> <div>%menu%</div> <div>%content%</div> </div> <div>%footer%</div> </body> </html>
As you can see, I have 4 place holders there, %header%, %menu%, %content% and %footer.
Now all I have to do is use str_replace to replace the place holders with content.
Here is an example of doing that
$html = file_get_contents("template.html"); $menu = "<ul><li>Option 1</li><li>Option 2</li></ul>"; $header = "<h1>This is the Header</h1><br />%menu%"; $content = "<p>This is some content.</p>"; $footer = "<small>This is the footer</small>"; $html = str_replace("%header%",$header,$html); $html = str_replace("%menu%",$menu,$html); $html = str_replace("%content%",$content,$html); $html = str_replace("%footer%",$footer,$html); echo $html;
As you can see, I make use of the placeholder within another placeholder as well. So the %menu% is also replace within the $header variable. Just note if you want to use it like that, you need to order the str_replace so that it will get replaced.
The resulting HTML will be:
<html> <body> <div><h1>This is the Header</h1><br /><ul><li>Option 1</li><li>Option 2</li></ul></div> <div> <div><ul><li>Option 1</li><li>Option 2</li></ul></div> <div><p>This is some content.</p></div> </div> <div><small>This is the footer</small></div> </body> </html>