一行代碼搞定
{if $smarty.now - $article.add_time lt 86400}[ NEW ]{/if}
參數解析
| 變量/常量 | 含義 | 單位 |
$smarty.now | 模板引擎內置:當前請求時間戳 | 秒 |
$article.add_time | 文章發布時間戳(來自數據庫) | 秒 |
86400 | 24 小時 = 60×60×24 | 秒 |
lt | Smarty 小於運算符(<) | - |
進階變體
1. 可配置天數(配置文件/常量)
{if $smarty.now - $article.add_time lt $smarty.const.NEW_TAG_HOURS * 3600}[ NEW ]{/if}
2. 帶樣式的標簽
{if $smarty.now - $article.add_time lt 86400}
<span class="badge badge-new">NEW</span>
{/if}
3. 列表頁批量判斷(section/foreach 通用)
{foreach $articles as $art}
<h3>
{$art.title}
{if $smarty.now - $art.add_time lt 86400}<span class="new">NEW</span>{/if}
</h3>
{/foreach}
注意事項
- 時間戳一致性:數據庫存儲、PHP 環境、Smarty 必須同一時區(建議統一 UTC 存儲,顯示時轉換)。
- 緩存影響:若頁面啟用 Smarty 緩存,
$smarty.now 會被緩存為編譯時時間,**導致標簽失效**。解決:{nocache}{if ...}{/if}{/nocache} 或不緩存該片段。
- 性能:極簡運算,無性能壓力。
延伸閱讀
- Smarty 模板中生成隨機數
- Smarty 模板中使用 PHP 函數及多函數鏈式調用
- Smarty 模板判斷數組為空
- Smarty 模板循環表格補充不全 td
- 程序中 define 常量在 Smarty 中使用
- Smarty for 循環擴展插件
- ThinkPHP volist 判斷最後一條記錄
- jQuery 滾動加載數據實現