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}

此代码连续显示 "This is a test." 特定次数 - 数据库中每个 post 用户显示一次。那部分工作完美。

但是,如果用户没有 post,则不会显示任何内容。这是有道理的,因为它应该只显示确实存在的 post 的文本。但是,如果使用 foreach 找不到任何内容,有没有办法让它给出某种类型的消息,例如 "There are no posts for this user"?

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}

为什么不只使用 smarty

使用{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