Database Templating Engine

Have you ever been annoyed by template engines that force you to keep your templates in flat files? Ever feel like that Content Management System you just created isn’t as dynamic as you originally thought? If you have ever felt like this, you may benefit from having your templates in a database.

Some argue that getting your templates from a database might slow down your site, as well as adding the overhead of having to open a database connection. However, if you’re using a PHP/MySQL driven site, you probably already have a open database link, so a few extra queries won’t slow down your small site much.

This tutorial will consist of two files, template.php and index.php. The first will have just have a few common functions (we could include these in index.php, but I prefer to separate function definitions from normal code). And the latter file, index.php, will connect to the database, and display the templates, amongst other things.

When the code is finished, I should be able to have a page like this on my site:

<?php

// Simple Templating Engine
// using a database tutorial.
// Written by Matt Eunson

// Define database variables – you have to change these
$Server = “localhost”;
$Username = “me”;
$Pass = “****”;
$Database = “template”;

// Now connect to the database
mysql_connect($Server, $Username, $Pass) or die(“Couldn’t connect to database.”);
mysql_selectdb($Database) or die(“Couldn’t select database: $Database”);

// Include the template functions
include_once “template.php”;

// Start our page
$Title = “Simple Template Engine using a Database”;
pageHeader($Title);

// Some content here…
echo “Welcome to my site.”;

// And close the page
pageFooter();

?>

Ok, now we know what we want, let’s get this show on the road!

{mospagebreak title=The Database}

First, let’s decide on our database structure. For what we need to do, we only require one table, which will be called “templates,” which will contain — yes, you guessed it — our templates. It’s a very simple table and only has 3 fields.

  • templateid: This is a unique identifier for the template.
  • name: Pretty self explanatory, the name of the template.
  • content: Again, pretty obvious, this is the HTML that makes up the template.

To create this table, you can use the following SQL:

CREATE TABLE `templates` (
`templateid` int(10) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default ”,
`content` text NOT NULL,
PRIMARY KEY (`templateid`)
) TYPE=MyISAM AUTO_INCREMENT=1 ;

Now we will populate it. We will only have 2 records, page_header & page_footer. These will be used to display the <html>, <head> and other needed tags in the page. This is simple so that you can understand what is happening, in reality, these would include logos, menus, and other elements. The advantage of this is that there is only one place where you edit the layout of your page, instead of having to do it in each HTML file. Anyway, here’s the SQL:

INSERT INTO `templates` VALUES (1, ‘page_header’, ‘<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>rn<html>rn<head>rn
<title>$pageTitle</title>rn</head>rn<body>’);
INSERT INTO `templates` VALUES (2, ‘page_footer’, ‘</body>rn</html>’);

Let’s go through page_header, which consists of the following html:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>$pageTitle</title>
</head>
<body>

As you can see, this includes a PHP variable, $pageTitle. These will be defined in the code before we display the template. But we’ll talk about that later. Now we have the database schema ready, we can start the basic functions for grabbing the template from the database.

template.php

The following code is in the file ‘template.php':

<?php

function fetchTemplate ($templateName) {

    $Query = “select content from templates where name=’$templateName'”;
    $tRes = mysql_query($Query);
    $Template = mysql_fetch_array($tRes);

    $Content = “echo “$Template[content]“;”;
    return $Content;

}

function pageHeader($pageTitle) {

    eval (fetchTemplate(“page_header”));

}

function pageFooter() {

    eval (fetchTemplate(“page_footer”));

}

?>

This may seem a bit confusing, so I’ll go over some parts more closely.

{mospagebreak title=Functions}

fetchTemplate function

<?php

function fetchTemplate ($templateName) {

    $Query = “select content from templates where name=’$templateName’ limit 1″;
    $tRes = mysql_query($Query);
    $Template = mysql_fetch_array($tRes);

    $Content = “echo “$Template[content]“;”;
    return $Content;

}

?>

First, this assembles the query, and selects one row’s content from the templates table, but only when it’s the one asked for by $templateName. Then we perform the query, and store the resource into the variable $tRes. Next, we use the mysql_fetch_array(); function to store the result of the query into an array. The next part maybe confusing, so firstly, I’ll explain what we do with the result of the function.

To show the template page_header, we would use this code:

<?php

eval (fetchTemplate(“page_header”));

?>

This uses a function you may not have come across before, eval();. You can find more information about this function at www.php.net/eval. Basically, it parses the string you pass it as PHP.

So if we go back up to the function fetchTemplate, and to the line $Content = “echo “$Template[content]“;”; we can see that this is preparing the string for use with eval(); What it is doing is putting echo “ in front of the template’s content, and “; after it. If we use the short template page_footer as an example, the value of $Content would be the following:

echo “</body>rn</html>”;

Therefore, when we use this string in eval, it would display the template’s content onto the user’s browser.

Other Functions

Now that we’ve got the hard bit out of the way, the pageHeader & pageFooter functions simply provide a nice easy function to put at the top & bottom of every page, instead of having to use eval (fetchTemplate(“page_header”));

However, if you remember the content of the page_header template, it contained a variable in it.

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>$pageTitle</title>
</head>
<body>

And if we look at the pageHeader function, the $pageTitle variable is passed into it, so when the code is eval’ed in the function, $pageTitle is replaced with whatever was passed to it in the function.

{mospagebreak title=A Sample Page}

Now we have all the functions created, we can simply use the code that I wrote at the beginning of this tutorial.

<?php

// Simple Templating Engine
// using a database tutorial.
// Written by Matt Eunson

// Define database variables – you have to change these
$Server = “localhost”;
$Username = “me”;
$Pass = “****”;
$Database = “template”;

// Now connect to the database
mysql_connect($Server, $Username, $Pass) or die(“Couldn’t connect to database.”);
mysql_selectdb($Database) or die(“Couldn’t select database: $Database”);

// Include the template functions
include_once “template.php”;

// Start our page
$Title = “My Site”;
pageHeader($Title);

// Some content here…
echo “Welcome to my site.”;

// And close the page
pageFooter();

?>

If you run this script, then the result will be the words “Welcome to my site” in your browser, along with the title “My Site” in your browser title bar.

And that just about rounds it up. Here you have a very simple, but working template engine using a database. You could extend this to include an admin control panel for editing your templates on the fly, or you could add new features to it. Anyway, thanks for reading this tutorial, and I hope you enjoyed it.

[gp-comments width="770" linklove="off" ]

chat sex hikayeleri Ensest hikaye