smarty技术最有特色的一点是开启了程序与美工分离的先例,使项目更易与维护和修改。现在很多网站都是采用或者仿照这种技术来实现的,这里有个实例
template.inc.php,代码如下:
<?php
class templets
{
var $filename; /*模板文件*/
var $content; /*输出内容*/
/****模板函数,功能是打开模板文件*****/
function temp( $tplfilename )
{
$this->filename = $tplfilename;
if ( file_exists( $this->filename ) )
{
$fd = fopen( $this->filename, "r" );
$this->content = fread( $fd, filesize( $this->filename ) );
fclose( $fd );
if ( strstr( $this->content, "<title>" ) && strstr( $this->content, "</title>" ) )
{
if ( !strstr( $this->content, "{site_extion_name}" ) )
{
$this->content = "[ ERROR:0 MISS TAG site_extion_name ]";
}
}
}
else
{
$this->content = "[ ERROR:1 THE TEMP FILE IS NOT EXISTS ]";
}
}
function gettemp( $tempcontent )
{
$this->content = $tempcontent;
}
/****标签注册 把key的值换成value******/
function assign( $key, $value )
{
$this->content = str_replace( "{".$key."}", $value, $this->content );
}
/**模块标签注册**/
function blockassign( $block_name, $values )
{
if ( is_array( $values ) )
{
ereg( "{".$block_name."}.*{/".$block_name."}", $this->content, $regs );
$str_block = substr( $regs[0], 2 + strlen( $block_name ), 0 - ( strlen( $block_name ) + 3 ) );
$str_replace = "";
$block_replace = "";
foreach ( $values as $subarr )
{
$str_replace = $str_block;
while ( list( $key, $val ) = key )
{
$str_replace = str_replace( "{".$key."}", $val, $str_replace );
}
$block_replace .= $str_replace;
}
$this->content = ereg_replace( "{".$block_name."}.*{/".$block_name."}", $block_replace, $this->content );
}
else
{
$this->content = ereg_replace( "{".$block_name."}.*{/".$block_name."}", "", $this->content );
}
}
/*输出替换后的页面*/
function show( )
{
return $this->content;
}
}
?>
标签是以“{”开始,以“}”结束的。
先创建模板文件template.htm
<html>
<head>
<title>{title}</title>
</head>
<body>
{example}
{tempfields}
{field1}
{feild2}
{/tempfields}
</body>
</html>
实现代码
<?
include("template.inc.php")
$temp= new templates();
$title = "test example";
$example = "<h1>example1</h1>";
$field1 = "test field1"
$field2 = "test field2"
$tempfields[] = array(
"field1" => $field1,
"field2" => $field2
);
$temp->temp("template.htm");
$temp->assign("title",$title);
$temp->assign("example",$example);
$temp-assignblock("tempfields",$tempfields);
$temp->show();
?>