I believe many friends still don’t know that you can call PHP’s built-in functions in smarty templates. Let’s take a look at its usage.
Template writing:
{'param1'|functionName:'param2':'param3'}
php function prototype:
echo functionName('param1','param2','param3');
Example:
{'1234567'|substr:'1':'2'}
The following is related to the order of parameters of the function
{'a'|str_replace:'A':'abcd'}
Extend directly to, directly Write a function call in php without registering a modifier.
Deeper research: I found that arrays can cause errors.
Assign an array array to Smarty, assuming that the delimiters of Smarty are '{' and '}'.
I have seen in many materials that when requiring the length of an array in Smarty, you can use the method call of adding |count after the array. That is, get the length of array through {array|count}. But when I was writing the template today, I found that I could not get the length of the array, but only a returned string Array. That is to say, only the result of {array} is returned, but the length of the array is not returned.
Looking at the smartyplugins folder, I found that there is no method related to count. In other words, count directly calls the method in php.
Later, through information on the Internet, I found that you can add @ in front of count to correctly obtain the length of the array. Further checking the source code of Smarty, we found that when Smarty processes the method name after the attribute adjuster, it will perform special processing on the one preceded by @. Therefore, we make a judgment: when calling a function defined in php in the attribute adjuster in Smarty, it can be expressed by adding @.
1. When testing the method of array type, it was found that if the @ symbol is not added, an error will occur. For example: to call the count method on an array to find out the length of the array, you can call {array|@count} like this, and to call the end method on an array to get the last set of data in the array, you can call {array|@ end}.
2. After testing the string-related functions, I found that it can be called normally with or without @.
3. Others have not been carefully tested.
Calling complex php functions in smarty is not encouraged, because the original intention of Smarty is to separate code and templates, and do not deviate from the original design intention.
Template writing:
{'param1'|functionName:'param2':'param3'}
php function prototype:
echo functionName('param1','param2' ,'param3');
Example:
{'1234567'|substr:'1':'2'}
The weird thing below is related to the order of parameters of the function
{ 'a'|str_replace:'A':'abcd'}
Smarty calls a custom function
To call a custom function, you need to use register_function() to register
Here is an example for you, Common string cutting
The function is as follows
Template call
www.bkjia.com