一个简单实现程序与美工分离的实例

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();

?>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值