Discuss how to get the length of the array in Smarty and explain how smarty calls the php function

  • 2020-06-15 07:57:22
  • OfStack

How do I get the length of an array in Smarty
An array array is assigned to Smarty, assuming that the delimiter for Smarty is '{' and '}'.
As you can see from many sources in Smarty, when you want the length of an array, you can add |count to the end of the array. That is, the length of array is obtained by {array|count}. But when I wrote the template today, I found that instead of getting the length of the array, I just got a string Array returned. This simply returns the result of {array}, not the length of its array.

Looking at the smarty\plugins folder, there is no method associated with count, that is, count calls the method in php directly.
Later, through the data on the network, it was found that count could be preceded by @, so as to obtain the length of the array correctly. Further step to look at the source of Smarty, Smarty found that when dealing with the method name behind the attribute modifier, it will do special treatment to the @ in front. So make the judgment: when a function defined in php is called from the property modifier in Smarty, it can be represented by adding @.

1. When testing the method with the type of array, it was found that it would be wrong without the @ sign. For example, to calculate the length of an array by calling the count method, you can call {array |@count}. If you want to call the end method to get the last set of data, you can call {array |@end}.
2, in the string of related functions to test, found that add @ can be called normally.
3. Others have not been tested seriously. Calling complex php functions in smarty is not encouraged, because Smarty is meant to separate code from templates, and templates should be assumed to be for interface designers, to whom too much complex logic is a torture.

Related articles: