0

以下是 书中给出的代码

    {* products_list.tpl *}
    {load_presentation_object filename="products_list" assign="obj"}

      {if $obj->mProducts}
      <table class="product-list" border="0">
      <tbody>
      {section name=k loop=$obj->mProducts}
      {if $smarty.section.k.index % 2 == 0}
      <tr>
      {/if}
    <td valign="top">
    <h3 class="product-title">
    <a href="{$obj->mProducts[k].link_to_product}">
    {$obj->mProducts[k].name}
    </a>
    </h3>
    <p>
    {if $obj->mProducts[k].thumbnail neq ""}
    <a href="{$obj->mProducts[k].link_to_product}">
    <img src="{$obj->mProducts[k].thumbnail}"
    alt="{$obj->mProducts[k].name}" />
    </a>
    {/if}
    {$obj->mProducts[k].description}
    </p>

    <p class="section">
    Price:
    {if $obj->mProducts[k].discounted_price != 0}
    <span class="old-price">{$obj->mProducts[k].price}</span>
    <span class="price">{$obj->mProducts[k].discounted_price}</span>
    {else}
    <span class="price">{$obj->mProducts[k].price}</span>
    {/if}
    </p>
    </td>
    {if $smarty.section.k.index % 2 != 0 && !$smarty.section.k.first ||
    $smarty.section.k.last}
    </tr>
    {/if}
    {/section}
    </tbody>
    </table>
    {/if}

我不清楚以下行

  {if $smarty.section.k.index % 2 == 0}

为什么要写上面的语句来查看索引是偶数还是奇数这对显示的表格有什么影响?

4

1 回答 1

2

它每两个数组项创建一个新的表格行。

 //open
 {if $smarty.section.k.index % 2 == 0}
   <tr>
 {/if}

 //close
 {if $smarty.section.k.index % 2 != 0 && !$smarty.section.k.first ||
     $smarty.section.k.last}
     </tr>
 {/if}

看看这个例子:

 echo "<table border='1'>\n";

 for($i = 0; $i<=10; $i++) {

   if ($i % 2 == 0) {
       echo "<tr>\n";
   }

   echo "<td> ". $i. "contents </td> \n"; 

   if ($i % 2 != 0) {
       echo "</tr> \n";
   }

}

 echo "<table />\n";
于 2013-06-21T15:19:21.983 回答