Templates should consist of 2 parts: getting data part and displaying data part.
While getting data, not a single character should be printed out.
If some errors occurred, display an error page.
Once you get all your data with no errors – it’s time to include a template. A template itself should be of 2 parts too: page template and common site template. By sorting things this way you’ll solve all your present and future templating problems.
A typical script may look like
1 2 3 4 5 6 7 8 9 10 11 |
<? //include our settings, connect to database etc. include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php'; //getting required data $DATA=dbgetarr("SELECT * FROM links"); $pagetitle = "Links to friend sites"; //etc //and then call a template: $tpl = "links.php"; include "template.php"; ?> |
where template.php
is your main site template, including common parts, like header, footer, menu etc:
1 2 3 4 5 6 7 8 9 10 |
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My site. <?=$pagetitle?></title> </head> <body> <div id="page"> <? include $tpl ?> </div> </body> </html> |
and links.php
is the actual page template:
1 2 3 4 5 6 |
<h2><?=$pagetitle?></h2> <ul> <? foreach($DATA as $row): ?> <li><a href="<?=$row['link']?>" target="_blank"><?=$row['name']?></a></li> <? endforeach ?> <ul> |
easy, clean and maintainable.
settings.php contains all common settings:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php $hostname_conn,$database_conn,$username_conn,$password_conn,$conn; $hostname_conn = "localhost"; $database_conn = "test"; $username_conn = "****"; $password_conn = "****"; $conn = mysql_connect($hostname_conn, $username_conn, $password_conn) or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("SET NAMES 'utf8'") or trigger_error(mysql_error(),E_USER_ERROR); $tpl = "default.php"; $pagetitle = ""; function dbgetarr(){ $a = array(); $args = func_get_args(); $query = array_shift($args); $query = str_replace("%s","'%s'",$query); foreach ($args as $key => $val) { $args[$key] = mysql_real_escape_string($val); } $query = vsprintf($query, $args); $res = mysql_query($query); if (!$res) { trigger_error("dbget: ".mysql_error()." in ".$query); } else { while($row = mysql_fetch_assoc($res)) $a[]=$row; } return $a; } ?> |