开发者

How to do this kind of templating in a single loop in smarty?

<ul>
{foreach from=$recommend item=value}
 <li><span><em>{$value['content']}</em></span></li>
{/foreach}
</ul>
<ul>
{foreach from=$recommend item=value}
 <li><h4>{$value['name']}</h4></li>
{/foreach}
</ul>

The above html can be generated by 1 loop if no开发者_JAVA百科t using smarty:

$html1 = $html2 = '<ul>';
foreach($recommend as $value)
{
  $html1 .= '<li><span><em>' . $value['content'] . '</em></span></li>';
  $html2 .= '<li><h4>' . $value['name'] . '</h4></li>';
}
$html1 .= '</ul>';
$html2 .= '</ul>';
$html = $html1 . $html2;

but I don't know how to do it when smarty is required.


This works with one loop:

<ul>
{foreach from=$recommend item=value}
  <li><span><em>{$value['content']}</em></span></li>
  {capture name=list2}
    <li><h4>{$value['name']}</h4></li>
  {/capture}
{/foreach}
</ul>
<ul>
{$smarty.capture.list2}
</ul>

But as the others already have written, I don't see the point in doing it, for your solution looks clearer.


As far as I can see, this can't be done in Smarty, because Smarty can't buffer contents like you can in PHP.

I can however not see why this would be necessary. It looks like unnecessary (and confusing) code cosmetics to me.


Here's my actual trouble,Category1~Category3 can only be available from $recommend:

<ul class="sort clearfix">
    <li class="curr"><span><em>Category1</em></span></li>
    <li><span><em>Category2</em></span></li>
    <li><span><em>Category3</em></span></li>
</ul>
<ul class="pic_txt_list clearfix">
    {recommend path="1" limit=3}
    {foreach from=$recommend item=value}
    <li>
        <script type="text/javascript">im_chat_now({$value['userid']},1)</script>
    </li>
    {/foreach}
    {/recommend}
    {recommend path="2" limit=3}
    {foreach from=$recommend item=value}
    <li>
        <script type="text/javascript">im_chat_now({$value['userid']},1)</script>
    </li>
    {/foreach}
    {/recommend}
    {recommend path="3" limit=3}
    {foreach from=$recommend item=value}
    <li>
        <script type="text/javascript">im_chat_now({$value['userid']},1)</script>
    </li>
    {/foreach}
    {/recommend}
</ul>


Unless you gain a significant speed improvement I suggest leaving it at 2 loops, that way it's easier to read.

If not you could use the {php} tags in smarty to execute raw php (Don't know if they are implemented by default though).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜