简体   繁体   中英

Understanding PHP Smarty template Foreach with nested While

I have the following code in my smarty template:

{foreach from=$categories item=l}
          <tr>----------START---------------</tr> <br/>

        {$l.category_name|strip_tags}
        {$l.sub_category}

        {while $l.sub_category}

            <td>{$l.category_name|strip_tags}</td>
            {foreach from=$l.sub_category item=k}
                <td>{$k.category_name|strip_tags}</td>
                <br/>
            {/foreach}

            <br/>
        {/while}

        ----------END---------------
            <br/>
        <br/>
    {/foreach}

This outputs:

----------START--------------- Teachers & StaffArray

----------END---------------

----------START--------------- PTA & Foundations

----------END---------------

----------START--------------- Enrichment Programs

----------END---------------

Teachers & Staff 5th Grade 6th Grade PTA & Foundations
Enrichment Programs

I Expected it to print out:

----------START--------------- Teachers & Staff

5th Grade 6th Grade

----------END---------------

----------START--------------- PTA & Foundations

----------END---------------

----------START--------------- Enrichment Programs

----------END---------------

Seems like the output gets printed after the for loop. I'm new to smarty templates and not really understanding why its printing like that.

In addition, I have another question:

{while $l.sub_category}

                {foreach from=$l.sub_category item=k}
                       <br/>
                    { $k.category_name|strip_tags }

                {/foreach}


               { assign var=l value=$l.sub_category}

                <br/>
            {/while}

I want to update the loop condition variable..but I'm not really sure how other then the assign method i did.

Any advice appreciated.

I think the problem may be down to your table structure, you open and close the tr before outputting the td tags and some browsers will then display the content out of order.

it should be along the lines of

{foreach cat loop}
  <tr>
    <td>
      {while loop}
    </td>
    <td>
      {foreach loop}
    </td>
  </tr>
{/close foreach loop}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM