简体   繁体   中英

PHP foreach to Smarty

I am trying to rewrite the RSS Feed Parser PHP Code to Smarty. The Smarty will not work for me somehow. Can somebody help me out please?

<ul>
<?php foreach ($feed['items'] as $item): ?>
    <li>
        <a href="<?= $item['link']; ?>"><?= $item['title']; ?></a>
    </li>
<?php endforeach; ?>
</ul>

My Smarty Code Updated: 12/07/13

{foreach name=aussen item=$feed.items from=$item}
    <li>
        <a href="{$item.link}">{$item.title}</a>
    </li>
{/foreach} 

There are a lot of issues with your smarty code. First, and foremost, you should NOT have php logic and smarty formatting in the same file. You should assign smarty variables separately and then call smarty for formatting. However if you stick with your existing stuff, you'll need to take into account the following:

  1. syntax of your foreach is wrong - the correct syntax is {foreach from=$variable item=$loop_var}

  2. php variables are not automatically available in smarty - you'll need to add smarty {assign} directive with a combination of {php}echo $php_var{/php}` to get php variable to smarty.

  3. syntax {php}$item['title']{/php} is invalid syntax for php and will result in syntax error.

On the whole, your approach is flawed. Smarty is good for a presentation (view) layer in an MVC app - and you're trying to combine everything into one file. Don't. If you are not sure how to set your application properly as MVC, then smarty is not for you.

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