Smarty循环部分,每4个添加<li> </li>但有时更少

时间:2013-10-02 18:44:30

标签: php smarty

我有循环生成:

< li > 1 2 3 < / li > 4 5 6 < li > 7 8 9 < / li > 10 11 12 < li > 13 14 15 < / li >

但我的问题是,有时循环结果会有较少的结果。最后,总是需要&lt; / li&gt;。所以它看起来像那样,

< li > 1 2 3 < / li > 4 5 6 < li > 7 8 < / li >

< li > 1 2 3 < / li > 4 5 6 < li > 7 < / li >

我已经提出了这样的代码,但它不能正常工作,

{section name=attribs loop=14}

{assign var=zamkniecie value=''}

{if $smarty.section.attribs.iteration % 5 == 0 or $smarty.section.attribs.iteration == 1}
        < li > {$smarty.section.attribs.iteration}
{/if}

{if $smarty.section.attribs.iteration % 4 == 0}
        < / li > {$smarty.section.attribs.iteration}
        {assign var=zamkniecie value=$smarty.section.attribs.iteration}
{/if}

{/section}

{if !$zamkniecie} < / li > {/if}

谢谢,

1 个答案:

答案 0 :(得分:0)

您可以使用.first代替.iteration == 1.last来查看循环的最后一次运行。对于这样的数学,使用从.index开始的0更有用,而不是从.iteration开始的1。您还想检查两个if语句中的% 3 - 在您的示例中,一个是5个组,另一个是4个!

我认为这应该有效:

{section name=attribs loop=14}

{* Open an item if this is the first entry (#0), or any that is divisible by 3 (#3, #6, etc) *}
{* Note that the .first is actually redundant, because 0 % 3 == 0 anyway *}
{if $smarty.section.attribs.index % 3 == 0 or $smarty.section.attribs.first}
        <li>
{/if}

{* Output the current item *}
{$smarty.section.attribs.iteration}

{* Close the current item if this is the last entry, or is the end of a group of 3 *}
{* The test is for indexes which leave a remainder of 2 when divided by 3: #2, #5, etc *}
{if $smarty.section.attribs.index % 3 == 2 or $smarty.section.attribs.last}
        </li>
{/if}

{/section}