我想创建foreach smarty loop with counter和3" if"里面的条件。 在我的计数器值大于3之后,我想重置计数器值并返回到If
的第一个条件这是我的代码
{foreach $itemscollection as $singleitem name=smartyloop}
{assign var="counter" value=$smarty.foreach.smartyloop.iteration}
{if $counter == 1}
<h1>I am the one</h1>
{/if}
{if $counter == 2}
<h1>I am second</h1>
{/if}
{if $counter == 3}
<h1>I am third</h1>
{/if}
{if $counter > 3}
{$counter = 1}
{/if]
{/foreach}
例如,如果我有4个元素放入foreach输出应该看起来像
I am the one
I am second
I am third
I am the one
现在它不工作,我不知道为什么。 有人可以帮助我,并告诉如何解决这个问题?
答案 0 :(得分:2)
{assign var=counter value=1}
{foreach $itemscollection as $singleitem name=smartyloop}
{if $counter == 1}
<h1>I am the one</h1>
{/if}
{if $counter == 2}
<h1>I am second</h1>
{/if}
{if $counter == 3}
<h1>I am third</h1>
{/if}
{if $counter > 3}
{assign var=counter value=1}
{/if]
{$counter++}
{/foreach}
这可能有效
答案 1 :(得分:2)
我知道这是一个旧的但是尝试使用counter作为smarty的自定义函数:
{foreach $itemscollection as $singleitem name=smartyloop}
{counter assign='pos'} {* assign counter to variable *}
{if $pos == 1}
<h1>I am the one</h1>
{/if}
{if $pos == 2}
<h1>I am second</h1>
{/if}
{if $pos == 3}
<h1>I am third</h1>
{counter start=0} {*reset counter*}
{/if}
{/foreach}
必须回到CMS Made Simple才能做出相关的事情;)
答案 2 :(得分:1)
尝试
{if $counter%3 eq 0 && $counter gt 2}
{assign var=counter value=1}
{/if}
答案 3 :(得分:0)
此解决方案正在运行 我不知道为什么,也许foreach检查从最后到第一的条件。
{foreach $blogscollection as $singleblog name=smartyloop}
{assign var="counter" value=$smarty.foreach.smartyloop.iteration}
{if $counter>3}
{assign var=counter value=1}
{/if}
{if $counter == 1}
<h1>I am the one</h1>
{/if}
{if $counter == 2}
<h1>I am the second</h1>
{/if}
{if $counter == 3}
<h1>I am the third</h1>
{/if}
{/foreach}
答案 4 :(得分:0)
<?php
$array=array(' the ','hap',' pop' ,' grand'); // assume this is your array to pass in for each
$says=array(' the one','second',' third'); // store your word to appear
$count=0;
foreach ($array as $arr){
if($count == 3) $count=0;
print "<h1>I am $says[$count]<h1>";
$count++;
}
?>
答案 5 :(得分:0)
You can use {cycle} http://www.smarty.net/docs/en/language.function.cycle.tpl
{cycle name="counter" values="1,2,3"}
Or you could use the Modulus(%) operator http://php.net/manual/en/language.operators.arithmetic.php
{$counter = ($smarty.foreach.smartyloop.iteration % 3) + 1}