tags:

views:

18

answers:

4
<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 not 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.

A: 

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.

Pekka
Smarty can buffer, with {capture} http://www.smarty.net/manual/en/language.builtin.functions.php#language.function.capture
JochenJung
A: 

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>
smarty
A: 

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).

Xeross
+1  A: 

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.

JochenJung
Nice, wasn't aware of this! +1
Pekka