Home > Article > Backend Development > ThinkPHP custom function solves the problem of adding and subtracting template tags, thinkphp template_PHP tutorial
This article describes the example of ThinkPHP custom function solving the method of adding and subtracting template tags. Share it with everyone for your reference. The details are as follows:
In actual projects, we often need to add and subtract label variables. However, in ThinkPHP, direct operation of template variables is not supported.
Fortunately, it provides a method of custom function, we can use custom function to solve the problem:
The syntax of ThinkPHP template custom function is as follows:
Format: {:function(…)} (Refer to the official help document: http://thinkphp.cn/Manual/196)
Using this, let's try addition and subtraction.
1. Define functions in ThinkPHP. Create a new common.php file in the common folder of the project (the system will load it automatically). Define two functions:
/** * 相加,供模板使用 * @param <type> $a * @param <type> $b */ function template_add($a,$b){ echo(intval($a)+intval($b)); } /** * 相减,供模板使用 * @param <type> $a * @param <type> $b */ function template_substract($a,$b){ echo(intval($a)-intval($b)); }
2. Use functions in templates:
Copy code The code is as follows: {:template_add($var1,$var2)}
The sum of variables var1 and var2 can be displayed.
It should be noted that if the variable is an array, it should be displayed like this:
Copy code The code is as follows: {:template_add($var[var1],$var[var2])}
Instead we usually use dot syntax.
I hope this article will be helpful to everyone’s PHP programming based on ThinkPHP.