Library tutorials & articles

Implementing a template based website

Templates in a DB

Our example (which is the same method used on this site), uses a number of templates stored either in a MySQL database, or in a directory folder. Each template contains static HTML content, as well as 'variable' tags that will be replaced with data by your PHP script. Lets take a look at one possible template:

<html>
<head>
<title>$pagetitle</title>
</head>
<body>
<h1>$pagetitle</h1>
<p>$pagetext</p>
</body>
</html>

As you can see, the template is made up of standard html elements, but also includes PHP variables, such as $pagetitle. These will eventually be replaced with values specified in our script. First however, we'll create a function to read these templates. In fact, we'll create two, one that uses the database method, and one that uses the directory method. You can use either, and both will work in the rest of the tutorial. First, lets create the database function.

function gettemplate($templatename) {
    global $templatecache;
    #check if template has already been loaded
    if ($templatecache[$templatename]!="") {
        #return cached version
        $template = $templatecache[$templatename];
    } else {
        #retrieve from database
        $query = mysql_query("SELECT content FROM templates WHERE name='$templatename'");
        if (mysql_num_rows($queryid)!=0) {
            #get the db field
            $template = mysql_result($query,"content");
            #replace \" with \\" ... this will be needed later in the script
            $template = str_replace("\"","\\\"",$template);
            #cache the contents
            $templatecache[$name] = $template;
        } else {
            $template="";
        }
    }
    return $template;
}

The function is very simple. First, it checks to see if we have a copy of the template in the cache (to save time accessing the db or file system again). If it hasn't, then it queries the database, and gets the content field. Please note that the previous code assumes that you have already established a connection to the database, and selected the database using mysql_connect and mysql_select_db. The function also requires a table in the database called templates, created using the following MySQL statement:

CREATE TABLE templates (
    id int unsigned NOT NULL AUTO_INCREMENT PRIMARY KEY,
    name varchar(30) NOT NULL,
    content LONGTEXT NOT NULL DEFAULT '',
    UNIQUE (name)
);

Comments

  1. 02 Jun 2005 at 09:58
    I have been trying to use php's inlude to include a template file which has been marked up with some php variables.  However when using include() the php parsing drops out.  This code keeps the parsing on.  Hope its of use to someone.

    $buffer = addslashes(get_include_contents('resultspage.htm'));
    eval("echo \"".$buffer."\";");

    function get_include_contents($filename) {
      if (is_file($filename)) {
          ob_start();
          include $filename;
          $contents = ob_get_contents();
          ob_end_clean();
          return $contents;
      }
      return false;
    }


    results page.htm:
    ....
                 <TD>{$output[num_responses]}</TD>
    ....
  2. 25 Feb 2004 at 10:24

    This sample is great BUT have a cuople of errors.
    The file test.php is missing "#include template.php";.
    The file template.php presents a variable $name that must be repalced with $templatename.
    If you solve this all will work fine.

  3. 22 Feb 2004 at 08:25
    The article was written before PHP had made this a requirement - I'll try and get the article updated to reflect these changes.
  4. 22 Feb 2004 at 08:24
    The article demonstrates two methods - one that uses a MySQL database to store the templates, and one that just uses a folder on the website.
  5. 26 Nov 2003 at 00:08

    I'm having a really hard time understanding how this works and I am not able to test it since I don't have a mysql server setup on my computer.  Does anyone have an example they could show me that doesn't involve connecting to a database?

  6. 06 Nov 2003 at 00:16
    The reason you get th error about $resultbits be undefined is because of the eval statement.

    eval("\$resultbits .= \"".gettemplate("ResultsBit")."\";");

    The operator underlined above takes to output of the gettemplate function and adds it to the $resultbits variable. However, in the script in the example does not give $resultbits a value before this eval statement, which causes the undefined error.

    To solve this probelm, simple set the $resultbits variable to an empty string at the beginning of the script usein the line  below:

    $resultbits="";

    This should solve the undefined variable error.

    As for the different spelling you mentioned, I beleive it is just a typing error.

    Hope this helps
    Happy Programming
    Defiant

  7. 05 Nov 2003 at 23:46
    To make the template system work, the most important thing to remember is that any PHP variable you use in the template must be defined prior to calling the template. Take the template bwlow, which I use in my sites:

    <html>
    <head>
     <title>$pagetitle</title>
     <link rel="stylesheet" type="text/css" href="../css/main.css">
     <script language="JavaScript" src="../scripts/global.js" type="text/javascript"></script>  
    </head>
    <body bgcolor=#470848  topmargin="0" leftmargin="0" marginheight="0" marginwidth="0" text=#D5D3D3>
     <table border=0 cellpadding=0 cellspacing=0 width="100%" height=100%>
      <tr height=90>
        <td width=146 align=center><img src="../images/bigbullet1.jpg" width=91 height=90></td>
        <td align=center><img src="../images/logo.gif" width="456" height="39"></td>
      </tr>
      <tr><td>
       <table background="../images/menucenter.jpg" cellpadding=0 cellspacing=0 border=0 height=100%>
        <tr><td class=bg><img src="../images/menutop.jpg"></td></tr>
        $pagemenu
        <tr><td height=99% valign=bottom><img src="../images/menubottom.jpg"></td></tr>
       </table>
      </td>
      <td valign=top>
       <center><img src="../images/line2.jpg" width=355 height=10><br>$pageheading</center><br>
       $pagecontent
      </td></tr>
     </table>
    </body>
    </html>

    The PHP variable, shown in bold face, must be defined before calling the template. Below is a typical page I would use with this template.

    <?php
    require "../php/global.inc";
    require "../php/about-menu.inc";

    $pagetitle = "About My Site";
    $pageheading="<h3>Please choose a area you would like to learn about.</h3>";
    $pagecontent = "";
    $pagemenu="";

    for ($i=0; $i < count($menunames); $i++) {
     eval("\$pagemenu .= \"".gettemplate("menu")."\";");
    }
    eval("echo \"".gettemplate("main")."\";");
    ?>

    The require statements import function unigue to my site. The point here is to show that I had to make sure that all the vairable I use in the template are defined. I also found that it works best if you give any variables you use in the templete to an empty string at the beginning of the script. It will take of some headaches later(trust me).

    I hope this helps. The example I have shown works on my system. If you have problems getting it working for your self, email me and I would be happy to help. My address is defiantapp_s@omnitelcom.com

    Happy Programming
    Defiant

    P.S. Sorry for the delay on posting a reply, been pritty busy. I will try to keep a closer eye in the future.
  8. 21 Oct 2003 at 10:38

    I find this article very interesting, but I don't succeed in making it working with an MS Access database and would be glad for any help or information how to do it.


    Stephan Wölfel
    stw@freesurf.fr

  9. 29 Sep 2003 at 10:39
    Could you pass on what you did to iron out the problems?
  10. 28 Sep 2003 at 01:41
    Just a short message to say how useful this topic was. I am currently developing a web site and found the information in this article very useful. It took a couple of tries to iron out the problems I had getting it started, but other then that, everything is working very well.

    Thanks for  the tip.

    Happy Programs
  11. 11 Jul 2003 at 16:43

    Hi, i'd like to ask a question - why browser returns a message about undefined variable $resultbits?
    btw, there is a misunderstanding with "resultsbit" instead of "resultbit". Anyways, it's quite nice

  12. 02 Jul 2002 at 02:01

    I have read the article and kinda understand. But how would you create the template using MS Access 97.

  13. 30 Oct 2001 at 05:17

    So is it not easy at all but sort of possible?


    I am very good with HTML, PHP, and some others, but I am just now starting ASP.  I got tired of SQL and moving on to some experimenting with ASP and OBDC.

  14. 29 Oct 2001 at 16:14

    Conversion of VBScript ASP isn't as easy, as it doesn't currently have an equivilant of the eval statement.... using JScript in an ASP file might well let you do that (I've never used it), in which case it should be fairly easy....

  15. 29 Oct 2001 at 04:08

    How well could you integrate this into ASP?


    I am working on an ASP project and would love to use something to this effect.  Could you make another tutorial on how to do this in ASP.  I am not to good at converting things to ASP quite yet, and  I have only created 3 things in ASP.


    Anything would help.

  16. 01 Jan 1999 at 00:00

    This thread is for discussions of Implementing a template based website.

Leave a comment

Sign in or Join us (it's free).

James Crowley James first started this website when learning Visual Basic back in 1999 whilst studying his GCSEs. The site grew steadily over the years while being run as a hobby - to a regular monthly audience ...

Related discussion

Related podcasts

  • EarthClassMail.com - Moving from LAMP to .NET 3.5

    Scott chats with Matt Davis, architect at EarthClassMail.com, about their move from a LAMP stack (Linux/Apache/mysql/PHP) to .NET 3.5. What's working, what's not, and what kinds of issues are they running into as their architect their solution.

Events coming up

  • Dec 3

    The Auckland PHP December meetup

    Auckland, New Zealand

    Topic: Magento E-Commerce platform Speaker: Robert Popovic, LERO9, Robert is the Technical Director and co-founder of LERO9. Robert attended the Electrotechnical Faculty at The University of Belgrade where he graduated with a Masters in Computer Science and Information Technology. Robert has worked exclusively in the field of web and software development throughout his career.

Want to stay in touch with what's going on? Follow us on twitter!