単純な実装プログラムと米工分離の例


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;
	}

}

?>

 
ラベルは「{」で始まり、「}」で終わります.
 
テンプレートファイルを作成する.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();

?>