Detailed explanation of ThinkPHP template IF tag usage

  • 2021-07-06 10:27:08
  • OfStack

The IF tag of ThinkPHP can be used to define complex conditional decisions, such as:


<if condition="($name eq 1) OR ($name gt 100) "> value1
<elseif condition="$name eq 2" />value2
<else /> value3
</if>

Note: Judgment expressions such as eq can be supported in condition attribute, which is the same as the comparison tag above, but it is not supported with " > "," < ", because it confuses template parsing, the following usage is wrong:


<if condition="$id < 5 "> value1
<else /> value2
</if>

Must be changed to:


<if condition="$id lt 5 "> value1
<else /> value2
</if>

In addition, we can use php code in the condition attribute, for example:


<if condition="strtoupper($user['name']) neq 'THINKPHP' "> ThinkPHP
<else /> other Framework
</if>

The condition property can support point syntax and object syntax, such as automatically determining whether an user variable is an array or an object:


<if condition="$user.name neq 'ThinkPHP' "> ThinkPHP
<else /> other Framework
</if>

Or know that user variables are objects


<if condition="$user:name neq 'ThinkPHP' "> ThinkPHP
<else /> other Framework
</if>

Note: Since php syntax is basically used in condition attribute of if tag, it will be more concise to use judgment tag and Switch tag as much as possible. In principle, switch and comparison tag can be solved without if tag as much as possible. Because switch and comparison tags can use variable adjusters and system variables. If the IF tag still cannot meet the requirements under some special requirements, you can use the native php code or PHP tag to write the code directly.

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "smarty Template Introduction Basic Tutorial" and "PHP Template Technology Summary".

I hope this article is helpful to the PHP programming based on ThinkPHP framework.


Related articles: