OK, now i know i will receive some scrutiny from some people here for "re-inventing the wheel", and they will tell me to just use Smarty, but, I have developed this simple template engine for my own purposes and i would like to share it with others here. Smart is very nice, and i would recommend it to anyone, but, this is a lot more simple, and a lot less bulky than Smarty, and is all i need. Plus, it was a great learning experience for me, so, below you can see how i built this template engine, and see a working demo here...
http://www.mct-hosting.com/template/mct/
go ahead and switch the template from default to mctStyle, and vise versa. i will post the code for both.
index.php
quicktemplate.php
/theme/default/index.tpl
/theme/mctSkin/index.tpl
to make this all work, you will need a mysql database. here is mine.
if you decide to use this template engine, please put something in the footer giving Method Computer Technologies credit.
http://www.mct-hosting.com/template/mct/
go ahead and switch the template from default to mctStyle, and vise versa. i will post the code for both.
index.php
PHP:
<?php #index.php
include ('../../admin/includes/phpconnect.php');
include('quicktemplate.php'); // Class definition
///////////////////// START, SWITCH THEME /////////////////////
// This will live in the admin panel once complete
if (isset($_POST['submitted'])) {
// Find the name of the theme that you want to change to
$getTheme = mysql_fetch_array(mysql_query("SELECT * FROM theme WHERE id=$_POST[newTheme] LIMIT 1"));
// Change the old theme to not active
$query = mysql_real_escape_string("UPDATE theme SET active=0 WHERE active=1 LIMIT 1");
// Make the selected theme active
$query2 = mysql_real_escape_string("UPDATE theme SET active=1 WHERE id=$_POST[newTheme] LIMIT 1");
// If both themes have been switched, show successful message
if(mysql_query($query) && mysql_query($query2)) {
echo "Successfully changed layout to $getTheme[themeName]!";
echo '<meta http-equiv="refresh" content="1;url='.$_SERVER['PHP_SELF'].'">';
// If there was an error changing status for the themes, show an error
} else {
echo "<strong>Error!</strong> There was a problem changing the layout.";
echo '<meta http-equiv="refresh" content="1;url='.$_SERVER['PHP_SELF'].'">';
/*echo "<strong>Error!</strong> There was a problem changing the layout.<br/><br/>MySQL said:<br /><pre>";
echo mysql_error();
echo "\n</pre>The query used was:<pre>\n$query</pre>";*/
die();
}
} else {
// find the theme
$findTheme = "SELECT * FROM theme WHERE active=1";
$themeResult = mysql_query ($findTheme);
$themeDefault = mysql_fetch_array ($themeResult, MYSQL_ASSOC);
$theme = 'theme/'.$themeDefault['themeName'].'/index.tpl';
//DELETE OR COMMENT OUT THE FOLLOWING STATEMENT BEFORE LAUNCH
//echo $theme."<br/><br/>\n";
echo "<form action=".$_SERVER['PHP_SELF']." method=\"post\">\n";
$query1 = mysql_query("SELECT * FROM theme WHERE active=1");
$rest = mysql_query("SELECT * FROM theme WHERE active=0");
echo "<select name='newTheme'>
<optgroup label=\"Current theme\">\n";
while ($query = mysql_fetch_array($query1)) {
echo "<option value='$query[id]'>$query[themeName]</option>\n";
}
echo "</optgroup>
<optgroup label=\"Switch to...\">\n";
while ($option = mysql_fetch_array($rest)) {
echo "<option value='$option[id]'>$option[themeName]</option>\n";
}
echo "</optgroup>
</select>
<input type=\"submit\" value=\"Change Template\" name=\"update\" style=\"font-size:10px;\" />
<input type=\"hidden\" name=\"submitted\" value=\"TRUE\" />
</form>\n";
} // End submitted check
///////////////////// END, SWITCH THEME /////////////////////
// Get the page title from the database for the array
$pT = mysql_fetch_array(mysql_query("SELECT title FROM pageTitle WHERE id=1"));
// Menu function
function menuLink() {
$limit = mysql_fetch_array(mysql_query("SELECT limitNum FROM menuLimit WHERE id=1"));
$sql = "SELECT * FROM Menu ORDER BY id ASC LIMIT 0,$limit[limitNum]";
$result = mysql_query($sql);
while($menuLink = mysql_fetch_array($result)) {
$html[] = '<li><a href="index.php?page='.$menuLink["l_name"].'"><strong>'.$menuLink["name"].'</strong></a></li>';
}
ob_start();
for($n = 0; $n <= 7; $n ++) {
echo $html[$n];
}
$data = ob_get_contents();
ob_end_clean();
return $data;
} // END menu function
// This is needed in case a link hasnt been selected
// This is for the default home page content
$query = "SELECT * FROM Menu WHERE id=1";
$result = mysql_query ($query);
$row = mysql_fetch_array ($result, MYSQL_ASSOC);
// This it the code needed for when a links is selected
$get = mysql_query("SELECT * FROM `Menu` WHERE l_name='$_GET[page]'") OR DIE(mysql_error());
$page = mysql_fetch_assoc($get);
// If a link hasnt been selected yet, default to the home page name
if(empty($_GET['page']) || $page['name'] == NULL){
$pageTitle = $row['name'];
} else { // If a link was selected, display the page title
$pageTitle = $page['name'];
}
// If a link hasnt been selected yet, default to the home page content
if(empty($_GET['page']) || $page['content'] == NULL){
$pageContent = $row['content'];
} else { // This will appear if a link has been selected
$pageContent = $page['content'];
}
//Build array for Title, Menu, Page Header and Content
$temp_data = array('main' => array('file' => $theme),
'title' => array('content' => $pT['title']),
'leftnav' => array('content' => menuLink()),
'pagetitle' => array('content' => '<strong>'.$pageTitle.':</strong>'),
'pagetxt' => array('content' => $pageContent));
$engine = new quick_template($temp_data);
echo $engine -> parse_template();
?>
quicktemplate.php
PHP:
<? #quicktemplate.php
class quick_template {
private $t_def;
public function parse_template($subset = 'main') {
$noparse = false;
$content = "";
$temp_file = $this->t_def[$subset]['file'];
if(isset($temp_file)) {
$fr = fopen($temp_file, "r");
if(strlen($temp_file) > 6) {
substr($temp_file, strlen($temp_file)-6);
}
if(strcasecmp($ext, ".tpl") != 0) {
$noparse = true;
}
if(!$fr) {
$content = "<!-- Error loading '$temp_file' //-->";
} else {
$content = fread($fr, filesize($temp_file));
}
@fclose($fr);
} else {
if(isset($this->t_def[$subset]['content'])) {
$content = $this->t_def[$subset]['content'];
} else {
$content = "<!-- Content for '$subset' not defined //-->";
}
}
if($noparse == true) {
$content = preg_replace("/\%([A-Z]*)\%/e", "quick_template::parse_template(strtolower('$1'))", $content);
}
return $content;
}
function __construct($temp = '') {
if(is_array($temp)) $this->t_def = $temp;
}
}
?>
/theme/default/index.tpl
HTML:
<html>
<head><title>%TITLE%</title></head>
<style>
ul {margin: 0px; padding: 0px;}
li {display: block; margin: 0px; padding: 0px;}
</style>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" valign="top">HEADER IMAGE HERE</td>
</tr>
<tr>
<td valign="top" width="150">
<ul>%LEFTNAV%</ul>
</td>
<td valign="top">
%PAGETITLE%<br>
%PAGETXT%
</td>
</tr>
<tr>
<td colspan="2" valign="top">Method Computer Technologies</td>
</tr>
</table>
</body>
</html>
/theme/mctSkin/index.tpl
HTML:
<html>
<head><title>%TITLE%</title></head>
<style>
ul {margin: 0px; padding: 0px;}
li {display: inline; margin: 5px 10px 5px 0px; padding: 0px;}
</style>
<body>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td valign="top">HEADER IMAGE HERE</td>
</tr>
<tr>
<td valign="top">
<ul>%LEFTNAV%</ul>
</td>
</tr>
<tr>
<td valign="top">
%PAGETITLE%<br>
%PAGETXT%
</td>
</tr>
<tr>
<td valign="top">Method Computer Technologies</td>
</tr>
</table>
</body>
</html>
to make this all work, you will need a mysql database. here is mine.
Code:
--
-- Table structure for table `Menu`
--
CREATE TABLE `Menu` (
`id` int(25) NOT NULL auto_increment,
`display` int(10) NOT NULL default '0',
`name` varchar(100) default NULL,
`l_name` varchar(100) default NULL,
`menuIcon` varchar(250) default NULL,
`content` text,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `Menu`
--
INSERT INTO `Menu` VALUES(1, 1, 'Home', 'Home', 'http://www.mct-hosting.com/images/uploads/menuIcons/home.png', '<p><span class="main_txt_head">What we offer:</span><br />MCT-Hosting.com takes the uncertainty out of hosting, and puts service, performance and value back in. No matter which hosting type or plan you choose, your site will receive 24/7 maintenance and protection. You will recieve the expert and friendly service that you deserve, from MCT-Hosting.<br /><br /><span class="main_txt_head">Overview:</span><br />At MCT-Hosting.com, we develop, run, maintain and support our hosting plans 24/7. So for safe, reliable and affordable web site hosting, play it smart. Just scan through the individual plans and choose the one that's right for you! <br /><br /><span class="note_txt">Note: Each month of hosting is paid for in advance and begins upon the purchase of this account. Cancellation of your hosting account will discontinue all future billings. Hosting fees are non-refundable.</span></p>');
INSERT INTO `Menu` VALUES(2, 0, 'Hosting', 'Hosting', 'http://www.mct-hosting.com/images/uploads/menuIcons/hosting.png', 'Put hosting info here.');
INSERT INTO `Menu` VALUES(3, 0, 'Domains', 'Domains', 'http://www.mct-hosting.com/images/uploads/menuIcons/domain.png', '<p>Put domain info here.</p>');
INSERT INTO `Menu` VALUES(4, 0, 'Other Services', 'OtherServices', 'http://www.mct-hosting.com/images/uploads/menuIcons/services.png', 'Put other services stuff here');
INSERT INTO `Menu` VALUES(5, 0, 'F. A. Q.', 'FAQ', 'http://www.mct-hosting.com/images/uploads/menuIcons/faq.png', '<span class="main_txt_head">Frequently Asked Questions</span><br />There are many important things to consider when choosing a hosting provider. Blow you can get the answers to many of your questions. If you do not see an answer to a question you have, please, feel free to <a href="..//">contact</a> our support team. <br /><br /><span class="main_txt_head">You have questions, we have answers.</span> <ol><li><a href="index.php?page=FAQSupport">Support</a></li><li><a href="index.php?page=FAQE-Mail">E-mail</a></li></ol><p> </p>');
INSERT INTO `Menu` VALUES(6, 0, 'About Us', 'AboutUs', 'http://www.mct-hosting.com/images/uploads/menuIcons/about.png', 'Put "about us" info here');
INSERT INTO `Menu` VALUES(7, 0, 'Contact Us', 'ContactUs', 'http://www.mct-hosting.com/images/uploads/menuIcons/contact.png', '<table border="0" cellspacing="5" cellpadding="0"><tbody><tr><td rowspan="2"><img src="../images/uploads/contact.png" border="0" alt=" " width="47" height="42" /></td><td><strong>Office:</strong></td><td>(480) 656-9965</td></tr><tr><td><strong>Cell:</strong></td><td>(480) 233-5006</td></tr></tbody></table>');
-- --------------------------------------------------------
--
-- Table structure for table `menuLimit`
--
CREATE TABLE `menuLimit` (
`id` int(25) NOT NULL auto_increment,
`limitNum` int(10) NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `menuLimit`
--
INSERT INTO `menuLimit` VALUES(1, 7);
-- --------------------------------------------------------
--
-- Table structure for table `pageTitle`
--
CREATE TABLE `pageTitle` (
`id` int(25) NOT NULL auto_increment,
`title` varchar(250) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
--
-- Dumping data for table `pageTitle`
--
INSERT INTO `pageTitle` VALUES(1, 'Test Template Engine');
-- --------------------------------------------------------
--
-- Table structure for table `theme`
--
CREATE TABLE `theme` (
`id` int(25) NOT NULL auto_increment,
`themeName` varchar(200) default NULL,
`active` int(10) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
--
-- Dumping data for table `theme`
--
INSERT INTO `theme` VALUES(1, 'default', 1);
INSERT INTO `theme` VALUES(2, 'mctSkin', 0);
if you decide to use this template engine, please put something in the footer giving Method Computer Technologies credit.
Last edited: