ok, I failed to build my own template, I wanted it to be fast and easy-to-use... I am posting code here with hope someone can finish it!
well, it's simple class include four functions... file(), area(), loop() and show()... the only part I couldn't done is the loop function, I really got suck trying to programming it, I still did not grub logic (also my education can't leave me time to do that... sorry) but other functions is fine...
here the source code and example!
template.core.php
<?Php
class tmpl {
var $file;
function file($file, $path = '.')
{
if (!is_dir($path. '/'))
{
die('Template: Cannot access directory "<i>./' .$path. '</i>"');
return FALSE;
}
$stream = fopen($path. '/' .$file, "r");
if (!$stream)
{
die('Template: Cannot access file "<i>' .$path. '/' .$file. '</i>"');
return FALSE;
}
$content = fread($stream, filesize($path. '/' .$file));
fclose($stream);
$count = count(explode('<include="', $content)) - 1;
if ($count != 0)
{
for ($i = 0; $i < $count; $i++)
{
$begin = strstr($content, '<include="');
$str_num = strpos($begin, '" />') - 10;
$name = substr($begin, 10, $str_num);
$include = '<include="' .$name. '" />';
$stream = fopen($path. '/' .$name, "r");
if (!$stream)
{
die('Template: Cannot access file "<i>' .$name. '</i>" to include');
return FALSE;
}
$to_include = fread($stream, filesize($path. '/' .$name));
fclose($stream);
$file = str_replace($include, $to_include, $content);
}
}
$this->file = $file;
}
function area($name, $state = 'hide')
{
if ($state == 'hide')
{
$begin= strstr($this->file, '<area="' .$name. '">');
$area = explode('</area="' .$name. '">', $begin);
$this->file = str_replace($area[0], '', $this->file);
$this->file = str_replace('</area="' .$name. '">', '', $this->file);
}
if ($state == 'show')
{
$this->file = str_replace('<area="' .$name. '">', '', $this->file);
$this->file = str_replace('</area="' .$name. '">', '', $this->file);
}
}
function loop($loop, $variable, $value)
{
/* here where I failed */
[url]http://www.phpbuilder.com/board/showthread.php?threadid=10262731[/url]
}
function show($var)
{
while (list($key, $val) = each($var))
{
$this->file = str_replace('$' .$key, $val, $this->file);
}
print($this->file);
}
/* end of class's code */ }
// example //
$tmpl = new tmpl;
$tmpl->file('index.htm');
$var['title'] = 'MyPRO';
$con = mysql_connect('localhost', 'root', '');
$query = mysql_query('SELECT * FROM phpbb2.phpbb_config');
while ($value = mysql_fetch_array($query))
{
$tmpl->loop('data', 'config_name', $value[0]);
$tmpl->loop('data', 'config_value', $value[1]);
}
mysql_free_result($query);
mysql_close($con);
$tmpl->area('first', 'show');
$tmpl->show($var);
?>
index.htm
<include="head.htm" />
<body />
<area="first"><center>header</center></area="first">
<ul>
<loop="data">
<li>config name = $config_name, config value = $config_value
</loop="data">
</ul>
</html>
head.htm
<html>
<head>
<title>$title</title>
</head>