简体   繁体   中英

smarty foreach how does it work correctly?

I have a problem with my smarty foreach. It does not output the right thing :SI tried many things but it never worked.

$data = array(
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test")
    );

    $smarty->assign('invTalents', $data);

    return array(
        array(
        'type' => 'html',
        'html' => $smarty->fetch('*****/*****/smarty.tpl'),

        ),
    );

in smarty.tpl I got this:

    <table class="designedTable" style="width:96%; font-size:11px;">
<thead>
    <tr>
        <td class="clear_first brdRight">
        </td><td class="white_last">
    </td></tr>
</thead>
<tbody>


    {foreach from=$invTalents item=data}
        <tr>
            <td class="clear_first brdRight">{$invTalents->data}</td><td class="white_last"><strong>0</strong></td>
        </tr>
        {/foreach}

</tbody>
<tfoot>
    <tr><td class="clear_first brdRight"></td><td class="white_last"></td></tr>
</tfoot>
</table>

What am I doing wrong? :)

@H34D, Please check below code.

$data = array(
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test"),
        array('name' =>  "name", 'value' => "test")
    );

$smarty->assign('invTalents', $data);

In your view you can access your array (ie invTalents) by this way. (General Smarty Behavior)

{foreach $invTalents as $inv} 
 {$inv.name} 
 {$inv.value} 
{/foreach}

So As Per Exact behavior of your view code you can access array like below. (As Per Your Code Structure)

{foreach $invTalents as $inv}
    <tr>
        <td class="clear_first brdRight">{$inv.name}</td><td class="white_last"><strong>0</strong></td>
    </tr>
{/foreach}
{foreach from=$invTalents item=data}

With this you loop through the invTalents variable and assign the current value to data . So in your output you need to use the data variable. Also you then need to access the array with the key(s) you defined in PHP, which are name and value .

{foreach from=$invTalents item=data}
    <tr>
        <td class="clear_first brdRight">{$data.name}</td><td class="white_last"><strong>{$data.value}</strong></td>
    </tr>
{/foreach}

More info and examples in the Smarty documentation: http://www.smarty.net/docsv2/de/language.function.foreach.tpl

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