php Smarty模板引擎之 if else的用法

作者:袖梨 2022-06-25


用法:
{if}{/if}

{if} {else}{/else}{/if}

解析引擎:

 代码如下 复制代码
// if
  $if_operators = array(">","<","==","===",">=","<=","!=","!==");
  $is_operator = false;
  $pattern_if = "/{$left_tag}ifs+((.*?)){$right_tag}/";
  preg_match_all($pattern_if,$content,$match_if);
  
  if (isset($match_if[1]) && is_array($match_if[1])) {
   
   foreach ($match_if[1] as $key_if=>$val_if) {
    foreach ($if_operators as $if_operator) {
     $items = explode($if_operator, $val_if);
     if (count($items) == 2) {
      $is_operator = true;
      $shift_left = substr($items[0], 0,1);
      $pop_left = substr($items[0], 1);
      $shift_right = substr($items[1], 0,1);
      
      $pop_right = substr($items[1], 1);
      $left_var = $shift_left == '$'? '$this->var_tpl_arr["'.$pop_left.'"]':$items[0];
      $right_var = $shift_right == '$'?'$this->var_tpl_arr["'.$pop_right.'"]':$items[1];
      $content = str_replace($match_if[0][$key_if], "", $content);
      break;
     } else {
      continue;
     }
    }
    if (!$is_operator) {
     $content = str_replace($match_if[0][$key_if], "", $content);
    }
   }
  }
  
  
  // if close
  $pattern_if = "/{$left_tag}/if{$right_tag}/";
  $replace_if = ";";
  if (preg_match($pattern_if, $content)) {
   $content = preg_replace($pattern_if, $replace_if, $content);
  }
  
  // else
  $pattern_else = "/{$left_tag}else{$right_tag}/";
  $replace_else = "";
  if (preg_match($pattern_else, $content)) {
   $content = preg_replace($pattern_else, $replace_else, $content);
  }
  
  // else close
  $pattern_else = "/{$left_tag}/else{$right_tag}/";
  $replace_else = "";
  if (preg_match($pattern_else, $content)) {
   $content = preg_replace($pattern_else, $replace_else, $content);
  }

模板表示方法:

 代码如下 复制代码





$var_left == {$var_left},$var_right == {$var_right}


test if >:$var_left>1


{if ($var_left>1)}
if > 条件成立!
{/if}

test if <:$var_left<5


{if ($var_left<5)}
if < 条件成立!
{/if}

test if ==:$var_left==$va_right


{if ($var_left==$va_right)}
if == 条件成立!
{else}
if = 条件不成立!
{/if}

解析后的缓存文件:

 代码如下 复制代码





$var_left == var_tpl_arr["var_left"];?>,$var_right == var_tpl_arr["var_right"];?>


test if >:$var_left>1


var_tpl_arr["var_left"] > 1) { ?>
if > 条件成立!www.111com.net>
;

test if

 代码如下 复制代码
<:$var_left<5


var_tpl_arr["var_left"] < 5) { ?>
if < 条件成立!
;

test if ==:$var_left==$va_right

 代码如下 复制代码


var_tpl_arr["var_left"] == $this->var_tpl_arr["va_right"]) { ?>
if == 条件成立!

if == 条件不成立!
;

相关文章

精彩推荐