萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php Smarty模板引擎 foreach循環

php Smarty模板引擎 foreach循環

   模板文件:

 代碼如下  

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>{$web_tile}</title>
</head>
<body>
{$article_title}
<br/>
  -- by {$author}
<hr/>
<br/>
{$content}
<br/>
-- publish @ {$time}

<br/>
<br/>
foreach test:

{foreach ( from=url key=b item=c )}
 <a href="index.php?artcle_id={==b}">{==c}</a>
{/foreach}

<br/>

</body>
</html>

  解析引擎:

 代碼如下   // var
  $pattern_var = "/{$left_tag}$([wd]+){$right_tag}/";
  $replace_var = '<?php echo $this->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 = '<?php foreach($this->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 = "<?php } ?>";
  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 = '<?php echo $$1;?>';
  
  if (preg_match($pattern_var, $content)) {
   $content = preg_replace($pattern_var, $replace_var, $content);
  }

  解析後:

 代碼如下  

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo $this->var_tpl_arr["web_tile"];?></title>
</head>
<body>
<?php echo $this->var_tpl_arr["article_title"];?>
<br/>
  -- by <?php echo $this->var_tpl_arr["author"];?>
<hr/>
<br/>
<?php echo $this->var_tpl_arr["content"];?>
<br/>
-- publish @ <?php echo $this->var_tpl_arr["time"];?>

<br/>
<br/>
foreach test:

<?php foreach($this->var_tpl_arr["url"] as $b => $c) { ?>
 <a href="index.php?artcle_id=<?php echo $b;?>"><?php echo $c;?></a>
<?php } ?>

<br/>

</body>
</html>

  使用:

 代碼如下  

<?php

require_once 'core/YATP.class.php';

copyright © 萬盛學電腦網 all rights reserved