您的位置:365bet体育备用网址器 > 应用 > php 模板写法

php 模板写法

2019-10-03 17:26

<?php
/* @author: zhuyubing@gmail.com */
class Template{
        var $code;
        function Template($template){
            $this->code = implode('', @file($template));
        }
        function assign($name,$var=null){
    if(is_string($name) && is_string($var)){
     $this->code = str_replace('{'.$name.'}', $var, $this->code);
    } else if(is_array($var)){
     list($this->code,$tmp,$end)=explode('<!--'.$name.'-->',$this->code);
     while(list(,$v)=each($var)){
      $t=$tmp;$k2=$v2='';
      while(list($k2, $v2) = each($v)){
           $t = str_replace('{'.$k2.'}', $v2,$t);
      }
      $this->code .= $t;
     }
     $this->code .= $end;    
    } else {    
     while (list ($k2, $v2) = each($name)){
           $this->code = str_replace('{'.$k2.'}', $v2, $this->code);
     }
    }
        }
        function display(){
                echo $this->code;
        }
}
?>
最简单的hello_world
准备一个php模版文件hello_world.html
<html>
<head>
<meta http-equiv="Content-Type" c />
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
</body>
</html>
接下来就是模版的翻译工作了
<?php
include('../include/template.php'); //包含模版核心类文件
$tpl=new Template('hello_world.html'); //参数为模版路径和文件名,可以使用相对路径,也可以使用绝对路径
$tpl->assign('title',"hello world!"); //将标签{title} 替换成hello world
$tpl->display();
?>

复制代码 代码如下:

模版中使用数组
test_array.html
<html>
<body>
<h3>{user} {email}</h3>
<h3>{user1} {email1}</h3>
</body>
</html>
模版处理文件
<?php
include('../include/template.php');
$tpl=new Template('test_array.html');
$user=array('user'=>'yubing','email'=>'test@sina.com');
$tpl->assign($user);
$tpl->assign('user1','jack');
$tpl->assign('email1','zhuyubing@gmail.com');
$tpl->display();
?>
简单的区块处理
block.html
<table width="400" border="1">
  <tr>
    <td>User Name</td>
    <td>E-Mail</td>
  </tr>
  <!--users-->
  <tr>
    <td>{name}</td>
    <td>{email}</td>
  </tr>
  <!--users-->
</table>
区块处理程序
block.php
<?php
include('../include/template.php');
$tpl=new Template('block.html');

<?php
/*template.class.php
@康盛微博 模板提取类 觉得这个模板好用 花些时间独立出来。 by 雷日锦
@看了一下ctt 这个模板 跟 phpcms的模板类似 难道?? ^_^ 嘿嘿!!!
@ 微博
@ 好东西大家共享 磕磕绊绊的提取出来 有问题请提出来
@ 模板文件默认为 .htm
$tpl = new template('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//开启rewrite 需要服务器支持
$tpl->rewrite_rule=array(array("/index.php/"),array("index.html")); //rewrite规则
$tpl->assign("indexurl","index.php");
$tpl->assign("str","我是字符串啦啦啦");
$tpl->assign("ec","我是被echo出来的");
$tpl->assign("subhtml","{subtpl ttt}这是用来引入一个模板文件的,这个就是引入ttt.htm");
$tpl->assign("a",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl->assign("i",1);
$tpl->display("index");
*/
if(!defined("CHARSET")) define("CHARSET","gb2312");//字符编码
if(!defined("DIR_TPL")) define("DIR_TPL","tpl");//默认模板目录
if(!defined("DIR_DATA")) define("DIR_DATA","data");//默认数据目录
if(!defined("DEBUG")) define("DEBUG",0);//默认运行模式
class template {
//note var
public $rewrite=false;//是否开启 伪静态 rewrite
public $rewrite_rule=array(); //设置伪静态规则
public $defaulttpldir;//默认的模板
public $tpldir;//模板目录
public $objdir;//编译缓存目录
public $tplfile;//模板文件
public $objfile;//编译文件
public $tplid=1;//模板编号
public $currdir='default';//当前风格目录
public $vars=array();//note 变量表
public $removeblanks=false;//移除空格
public $stdout='display';//输出类型
function __construct($tplid, $currdir) {
$this->template($tplid, $currdir);
}
function template($tplid, $currdir) {
ob_start();
if(file_exists(DIR_TPL.'/'.$currdir)) {
$this->currdir = $currdir;
$this->tplid = $tplid;
} else {
$this->currdir = 'default';
$this->tplid = 1;
}
$this->defaulttpldir = DIR_TPL.'/default';
$this->tpldir = DIR_TPL.'/'.$this->currdir;
$this->objdir = DIR_DATA.'/cache/tpl';
if(version_compare(PHP_VERSION, '5') == -1) {
register_shutdown_function(array(&$this, '__destruct'));
}
}
//note publlic
function assign($k, $v) {
$this->vars[$k] = $v;
}
//note publlic
function display($file) {
extract($this->vars, EXTR_SKIP);
include $this->getObj($file);
}
function getObj($file, $tpldir = '') {
$subdir = ($pos = strpos($file, '/')) === false ? '' : substr($file, 0, $pos);
$file = $subdir ? substr($file, $pos 1) : $file;
$this->tplfile = ($tpldir ? $tpldir : $this->tpldir).'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
$this->objfile = $this->objdir.'/'.($tpldir ? '' : $this->tplid.'_').($subdir ? $subdir.'_' : '').$file.'.php';
//note 默认目录
if(@filemtime($this->tplfile) === FALSE) {
$this->tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
}
//note 判断是否比较过期
if(!file_exists($this->objfile) || DEBUG && @filemtime($this->objfile) < filemtime($this->tplfile)) {
$this->compile();
}
return $this->objfile;
}
function getTpl($file) {
$subdir = ($pos = strpos($file, '/')) === false ? '' : substr($file, 0, $pos);
$file = $subdir ? substr($file, $pos 1) : $file;
$tplfile = $this->tpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
if(@filemtime($tplfile) === FALSE) {
$tplfile = $this->defaulttpldir.'/'.($subdir ? $subdir.'/' : '').$file.'.htm';
}
return $tplfile;
}
function compile() {
$var_regexp = "@?\$[a-zA-Z_]w*(?:[[w."'[]$] ])*";
$vtag_regexp = "<?=(@?\$[a-zA-Z_]w*(?:[[w."'[]$] ])*)?>";
$const_regexp = "{([w] )}";
$template = file_get_contents($this->tplfile);
for($i = 1; $i <= 3; $i ) {
if(strpos($template, '{subtpl') !== FALSE) {
if(DEBUG == 2) {
$template = str_replace('{subtpl ', '{tpl ', $template);
} else {
$template = preg_replace("/[nrt]*{subtpls ([a-z0-9_:/] )}[nrt]*/ies", "file_get_contents($this->getTpl('\1'))", $template);
}
}
}
$remove = array(
'/(^|r|n)/*. ?(r|n)*/(r|n)/is',
'///note. ?(r|n)/i',
'///debug. ?(r|n)/i',
'/(^|r|n)(s|t) /',
'/(r|n)/',
);
$this->removeblanks && $template = preg_replace($remove, '', $template);
$template = preg_replace("/<!--{(. ?)}-->/s", "{\1}", $template);
$template = preg_replace("/{($var_regexp)}/", "<?=\1?>", $template);
$template = preg_replace("/{($const_regexp)}/", "<?=\1?>", $template);
$template = preg_replace("/(?<!<?=|\\)$var_regexp/", "<?=\0?>", $template);
$template = preg_replace("/<?=(@?\$[a-zA-Z_]w*)(([[\$[]w] ]) )?>/ies", "$this->arrayindex('\1', '\2')", $template);
$template = preg_replace("/{{eval (.*?)}}/ies", "$this->stripvtag('<? \1?>')", $template);
$template = preg_replace("/{eval (.*?)}/ies", "$this->stripvtag('<? \1?>')", $template);
$template = preg_replace("/[nrt]*{echos (. ?)}[nrt]*/ies", "$this->stripvtag('<? echo \1; ?>','')", $template);
$template = preg_replace("/{for (.*?)}/ies", "$this->stripvtag('<? for(\1) {?>')", $template);
$template = preg_replace("/{elseifs (. ?)}/ies", "$this->stripvtag('<? } elseif(\1) { ?>')", $template);
for($i=0; $i<2; $i ) {
$template = preg_replace("/{loops $vtag_regexps $vtag_regexps $vtag_regexp}(. ?){/loop}/ies", "$this->loopsection('\1', '\2', '\3', '\4')", $template);
$template = preg_replace("/{loops $vtag_regexps $vtag_regexp}(. ?){/loop}/ies", "$this->loopsection('\1', '', '\2', '\3')", $template);
}
$template = preg_replace("/{ifs (. ?)}/ies", "$this->stripvtag('<? if(\1) { ?>')", $template);
$template = preg_replace("/{tpls (w ?)}/is", "<? include $this->getObj("\1");?>", $template);
$template = preg_replace("/{tpls (. ?)}/ise", "$this->stripvtag('<? include $this->getObj("\1"); ?>')", $template);
$template = preg_replace("/{tmptpls (w ?)}/is", "<? include $this->getObj("\1", $this->objdir);?>", $template);
$template = preg_replace("/{tmptpls (. ?)}/ise", "$this->stripvtag('<? include $this->getObj("\1", $this->objdir); ?>')", $template);
$template = preg_replace("/{else}/is", "<? } else { ?>", $template);
$template = preg_replace("/{/if}/is", "<? } ?>", $template);
$template = preg_replace("/{/for}/is", "<? } ?>", $template);
$template = preg_replace("/$const_regexp/", "<?=\1?>", $template);//note {else} 也符合常量格式,此处要注意先后顺序
$template = preg_replace("/(\$[a-zA-Z_]w [)([a-zA-Z_]w )]/i", "\1'\2']", $template);
$fp = fopen($this->objfile, 'w');
fwrite($fp, $template);
fclose($fp);
}
function arrayindex($name, $items) {
$items = preg_replace("/[([a-zA-Z_]w*)]/is", "['\1']", $items);
return "<?=$name$items?>";
}
function stripvtag($s) {
$vtag_365bet在线官网,regexp = "<?=(@?\$[a-zA-Z_]w*(?:[[w."'[]$] ])*)?>";
return preg_replace("/$vtag_regexp/is", "\1", str_replace("\"", '"', $s));
}
function loopsection($arr, $k, $v, $statement) {
$arr = $this->stripvtag($arr);
$k = $this->stripvtag($k);
$v = $this->stripvtag($v);
$statement = str_replace("\"", '"', $statement);
return $k ? "<? foreach((array)$arr as $k => $v) {?>$statement<?}?>" : "<? foreach((array)$arr as $v) {?>$statement<? } ?>";
}
function __destruct() {
$content = ob_get_contents();
//处理 rewrite
if($this->rewrite) {
$arr=$this->rewrite_rule;
$s=$arr[0];
$e=$arr[1];
$content=preg_replace($s,$e,$content);
}
ob_end_clean();
echo $content;
}
}
$tpl = new template('skin',"default");
$tpl->objdir='tpp';
$tpl->rewrite=true;//开启rewrite 需要服务器支持
$tpl->rewrite_rule=array(array("/index.php/"),array("index.html")); //rewrite规则
$tpl->assign("indexurl","index.php");
$tpl->assign("str","我是字符串啦啦啦");
$tpl->assign("ec","我是被echo出来的");
$tpl->assign("subhtml","{subtpl ttt}这是用来引入一个模板文件的,这个就是引入ttt.htm");
$tpl->assign("a",array('dasdasd'.'bbbbbbb','cccccccccccccc'));
$tpl->assign("i",1);
$tpl->display("index");
?>

$users=array(
  array('name'=>'jack','email'=>'test@example.com'),
  array('name'=>'tom','email'=>'tom@sina.com')
  );  
$tpl->assign('users',$users);
$tpl->display();
?>
模版包含测试
<html xmlns=";
<head>
<meta http-equiv="Content-Type" c />
<title>{title}</title>
</head>
<body>
<h1>{title}</h1>
    <p>{block}</p>
</body>
</html>
模版包含处理程序
<?php
include('../include/template.php');
$tpl=new Template('block.html');
$users=array(
array('name'=>'jack','email'=>'test@example.com'),
array('name'=>'tom','email'=>'zhuyubing@gmail.com'),
);
$tpl->assign('users',$users);
$block=$tpl->code;
$tpl->Template('main.html');
$tpl->assign('block',$block);
$tpl->assign(array('title'=>'测试多模版文件'));
$tpl->display();
?>

新建 tpl/default/index.html

复制代码 代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ";
<html xmlns=";
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
1.字符串赋值 :<br />
{$str}
<br />
2.数组赋值 :<br />
{loop $a $v}{$v},{/loop}
或者<br />
{loop $a $key $val }{$val},{/loop}

3.{$subhtml}<br />
{subtpl ttt}<br />
4.原来我是{$indexurl } 现在我被变成了index.php<br />
5.我还可以 echo 出来呢<br />
{echo $ec}<br />
6.其实我还可以加减乘除的 6*7*8
{echo 6*7*8;}
7.常用的就这些了 还有什么不懂的 <br />

</body>
</html>

新建 tpl/default/ttt.html
新建 tpp目录 ok了

本文由365bet体育备用网址器发布于应用,转载请注明出处:php 模板写法

关键词: