在模板中需根据数组是否为空决定是否渲染列表、显示“暂无数据”等。
{if $array|@count gt 0}
{foreach $array as $item}
<li>{$item}</li>
{/foreach}
{else}
<p>暂无数据</p>
{/if}
@count:@ 表示作用于整个数组而非单个元素gt 0:大于 0(也可用 neq 0)Countable{if $array neq ""}
有数据
{/if}
缺点:
"" 时判定为空(PHP 数组转字符串触发 Notice 并返回 "Array")[''](含一个空字符串元素)与真空数组<?php
$smarty->assign('hasItems', !empty($items));
$smarty->assign('items', $items);
{if $hasItems}
{foreach $items as $item}...{/foreach}
{else}
暂无数据
{/if}
{if $collection|@count}
...
{/if}
{* 或 *}
{if $collection|@count gt 0}
...
{/if}
Smarty 3+ @count 支持实现 Countable 接口的对象、Traversable 遍历器。
✅ 推荐:
{if $arr|@count}或 PHP 端预计算$hasData
❌ 不推荐:{if $arr neq ""}语义模糊、依赖实现细节