【phpstudy】php Smarty模板引擎 foreach循环

更新时间:2019-02-22    来源:smarty模板    手机版     字体:

【www.bbyears.com--smarty模板】

模板文件:

 代码如下





{$web_tile}


{$article_title}


  -- by {$author}





{$content}


-- publish @ {$time}





foreach test:

{foreach ( from=url key=b item=c )}
 {==c}
{/foreach}



解析引擎:

 代码如下 // var
  $pattern_var = "/{$left_tag}\$([wd]+){$right_tag}/";
  $replace_var = "var_tpl_arr["$1"];?>";
  
  if (preg_match($pattern_var, $content)) {
   $content = preg_replace($pattern_var, $replace_var, $content);
  }
  
  // foreach
  preg_match_all("/{$left_tag}foreachs+([^{]+?){$right_tag}/is", $content, $match_foreach);
  if (isset($match_foreach[1]) && is_array($match_foreach)) {
   foreach($match_foreach[1] as $match_key => $match_value) {
    $split_foreachs = array_filter(preg_split("/s+/is", $match_value));
    $new_foreach_tag = array();
    foreach($split_foreachs as $split_foreach) {
     $split = explode("=", $split_foreach);
     if (count($split == 2)) {
      if(in_array($split[0], array("from","item","key"))) {
//过滤标签 不存在过滤
       $new_foreach_tag[$split[0]] = $split[1];
      }
     }
    }
    
    $from = $key = $item = "";
    extract($new_foreach_tag);
    $key = ($key) ? "$".$key." =>" : "" ;
    $replace_foreach = "var_tpl_arr["".$from.""] as ".$key." $".$item.") { ?>";
    $content = str_replace($match_foreach[0][$match_key], $replace_foreach, $content);
    
   }
  }
  
  $pattern_foreach = "/{$left_tag}/foreach{$right_tag}/";
  $replace_foreach = "";
  if (preg_match($pattern_foreach, $content)) {
   $content = preg_replace($pattern_foreach, $replace_foreach, $content);
  }
  
  // var in statement
  $pattern_var = "/{$left_tag}==([wd]+){$right_tag}/";
  $replace_var = "";
  
  if (preg_match($pattern_var, $content)) {
   $content = preg_replace($pattern_var, $replace_var, $content);
  }

解析后:

 代码如下





<?php echo $this->var_tpl_arr["web_tile"];?>


var_tpl_arr["article_title"];?>


  -- by var_tpl_arr["author"];?>





var_tpl_arr["content"];?>


-- publish @ var_tpl_arr["time"];?>





foreach test:

var_tpl_arr["url"] as $b => $c) { ?>
 ">



使用:

 代码如下

require_once "core/YATP.class.php";

$app = new YATP();
date_default_timezone_set("Asia/Shanghai");
$app->is_cache = false;

$article_title = "yet,it is a simple template engine";
$author = "sanwhiteyu@tencent.com";
$web_tile = "just test ";
$content = "It is easy to write a simple template engine for yourself,what u can do is try to do it!";
$time = date("Y-m-d H:i:s",time());

$url = array(
  "url1"=>http://www.111cn.net,
  "url2"=>"http://www.baidu.com",
);

$app->assign("article_title",$article_title);
$app->assign("author",$author);
$app->assign("web_tile",$web_tile);
$app->assign("content",$content);
$app->assign("time",$time);
$app->assign("url",$url);
$app->display("index.html");


// end of script效果:

 

本文来源:http://www.bbyears.com/jiaocheng/48190.html