You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Twig中按指定日期展示不同内容?

解决Twig按特定日期展示不同内容的问题

你提供的代码无效的原因是:内层的{% if "Sunday" %}这类判断只是检查字符串本身是否为真(Twig中非空字符串默认判定为true),所以无论当前是星期几,都会执行第一个分支的内容。

以下是两种可行的实现方式:

方式一:先存储当前星期到变量(可读性更高)

{% set current_day = "now"|date("l") %}
{% if current_day == "Sunday" %}
    Sunday content
{% elseif current_day == "Tuesday" %}
    Tuesday content
{% elseif current_day == "Wednesday" %}
    Wednesday content
{% else %}
    default content
{% endif %}

方式二:直接在条件中比较(更简洁)

{% if "now"|date("l") == "Sunday" %}
    Sunday content
{% elseif "now"|date("l") == "Tuesday" %}
    Tuesday content
{% elseif "now"|date("l") == "Wednesday" %}
    Wednesday content
{% else %}
    default content
{% endif %}

说明:"now"|date("l") 会返回当前星期的完整英文名称(如Sunday、Monday),通过和目标星期字符串做相等判断,就能实现按日期展示对应内容的需求。

内容的提问来源于stack exchange,提问作者Nickinatorz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 22:15:40