Smarty is a very popular template in php development. In the past, I published an article on the development example of php smarty Chinese intercept plug-in to show you how to develop the smarty plug-in, this article will share with you how to create a for loop extension plug-in for the smarty template, in terms of our daily program development.
First, let's talk about how to use this for loop extension. When changing a previous website today, we need to make a for loop in the smarty template for some specific reasons, although smarty can be in the template with {php }...... {/php} labels are used to directly write the php statement syntax. However, because the values of the variables in the template are used in the loop, but the php statements directly written in the template cannot obtain the values in the template variables, this idea will not work, finally, I thought, can I use the for loop directly in the smarty template?
The following describes how to add a for loop extension plug-in to smarty.
(1) create a file named block. for. php In the plugins directory under the installation directory of the smarty template, and enter the following code in the file:
<? Phpfunction smarty_block_for ($ params, $ content, & $ smarty) {if (is_null ($ content) {return ;}$ start = 0; $ to = 0; $ step = 1; foreach ($ params as $ k => $ v) {switch ($ k) {case 'start': case 'to': case 'step ': $ k = (int) $ v; break; default: $ smarty-> trigger_error ("textformat: Unknown attribute: '$ k '");}} $ _ output = ''; for ($ _ x = $ start; $ _ x <= $ to; $ _ x + = $ step) {$ _ output. = $ content. "\ n \ r";} return $ _ output ;}
(2) then we can directly use the for loop in the smarty template. The author's use case is as follows:
PHP file code:
$ Vote = '[['; // in the template, I want to convert these three symbols into three five-star images $ smarty-> assign ('vote', $ vote );
Some code of the smarty template file:
{if false!==$vote|@stripos:'['}{for start=1 to=$vote|@strlen step=1}{/for}{/if}
OK. Solve the above problem. Similarly, if you still need to expand more functions for smarty, the same method can basically be implemented.
Articles you may be interested in
- The cycle table in the smarty template contains incomplete td
- Use php functions in the smarty template and how to use multiple functions for a variable in the smarty Template
- The last record of the volist loop in the thinkphp Template
- Method for judging null array in the smarty Template
- Add the latest tag to the information in the smarty Template
- Smarty template retention variable Summary
- Php smarty Chinese interception plug-in development example
- How to generate a random number in the smarty Template