php Smarty模板引擎之 if else的用法
php Smarty模板引擎之 if else的用法
用法:{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], "<?php if({$left_var} {$if_operator} {$right_var}) { ?>", $content); break; } else { continue; } } if (!$is_operator) { $content = str_replace($match_if[0][$key_if], "<?php if({$val_if}) { ?>", $content); } } } // if close $pattern_if = "/{$left_tag}/if{$right_tag}/"; $replace_if = "<?php } ?>;"; if (preg_match($pattern_if, $content)) { $content = preg_replace($pattern_if, $replace_if, $content); } // else $pattern_else = "/{$left_tag}else{$right_tag}/"; $replace_else = "<?php } 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); } |
模板表示方法:
代码如下 | |
<br/> <br/> $var_left == {$var_left},$var_right == {$var_right}<br/><br/> test if >:$var_left>1 <br/> {if ($var_left>1)} <b>if > 条件成立!</b> {/if} <br/> test if <:$var_left<5 <br/> {if ($var_left<5)} <b>if < 条件成立!</b> {/if} <br/> test if ==:$var_left==$va_right <br/> {if ($var_left==$va_right)} <b>if == 条件成立!</b> {else} <b><font color=red>if = 条件不成立!</font></b> {/if} |
解析后的缓存文件:
代码如下 | |
<br/> <br/> $var_left == <?php echo $this->var_tpl_arr["var_left"];?>,$var_right == <?php echo $this->var_tpl_arr["var_right"];?><br/><br/> test if >:$var_left>1 <br/> <?php if($this->var_tpl_arr["var_left"] > 1) { ?> <b>if > 条件成立!www.111cn.net</b> <?php } ?>; <br/> |
test if
代码如下 | |
<:$var_left<5 <br/> <?php if($this->var_tpl_arr["var_left"] < 5) { ?> <b>if < 条件成立!</b> <?php } ?>; <br/> |
test if ==:$var_left==$va_right
代码如下 | |
<br/> <?php if($this->var_tpl_arr["var_left"] == $this->var_tpl_arr["va_right"]) { ?> <b>if == 条件成立!</b> <?php } else { ?> <b><font color=red>if == 条件不成立!</b></b> <?php } ?>; |