PHP/Smarty-识别一个空的“;foreach”;


PHP / Smarty - Identifying an empty "foreach"

这是我当前的代码:

{php} foreach($result as $key=>$value)
{ echo "<div class='internalpadding'>";
{/php}
This is a test.
{php} } {/php}

这段代码在一行中显示"这是一个测试"特定的次数——用户在数据库中的每个帖子一次。那部分工作得很好。

然而,如果用户没有帖子,则根本不会显示任何内容。这是有道理的,因为它应该只是显示确实存在的帖子的文本。但是,如果使用foreach没有发现任何内容,我有没有办法让它发出某种类型的消息,比如"没有针对该用户的帖子"?

使用{foreachelse}

{foreach $result as $post}
    <h2>{$post->title}</h2>
    <p>{$post->text}</p>
{foreachelse}
    There are no posts for this user
{/foreach}

官方文件:https://www.smarty.net/docsv2/en/language.function.foreach.tpl

if ($result == null)
 echo "There are no posts for this user" ;
else {
       foreach($result as $key=>$value)
         { echo "<div class='internalpadding'>";
           echo "This is a test" ; }
}
{if $result|@count == 0}
 There are no posts for this user
{else}
  {foreach from=$result item=$post}
    <h2>{$post->title}</h2>
    <p>{$post->text}</p>
  {/foreach}
{/if}

为什么不使用智能