【问题标题】:Integer comparison with Twig Symfony 4与 Twig Symfony 4 的整数比较
【发布时间】:2020-05-10 19:14:28
【问题描述】:

我正在尝试在 Symfony 上使用 Twig 进行一些比较,以显示具有不同风格的文本,但我得到了一个奇怪的结果。该值来自我的实体(上下文)函数:

    public function getDaysToExpire(): int
    {
        $creationDate = $this->created_at;
        $duration = $this->duration;
        $finalDate = $creationDate->modify('+' . $duration . ' days');
        $currentDate = new \DateTime();
        $difference = $currentDate->diff($finalDate);

        return $difference->days;
    }

它按预期工作并返回一个整数作为结果。

我的树枝上有:

{% if context.getDaysToExpire > 5 %}
   <p class="context-days">Jours restants : {{ context.getDaysToExpire }}</p>
{% else %}
   <p class="context-days">Jours restants : <span class="bolder">{{ context.getDaysToExpire }}</span></p>
{% endif %}

如果我不使用 if 子句,我会从 context.getDaysToExpire 中获得正确的值。但是,使用这段代码,我得到了一个奇怪的结果:第一个条件为 + 30,第二个条件为 + 随机值。

我做错了什么?

【问题讨论】:

  • 使用 $creationDate->modify 你实际上改变了 DateTime 对象。如果您调用此方法 2 次,您将添加 2 次持续时间。

标签: symfony twig comparison


【解决方案1】:

这应该可以工作

public function getDaysToExpire(): int
{
    $creationDate = clone $this->created_at; // prevent modification on $this->created_at
    $duration = $this->duration;
    $finalDate = $creationDate->modify('+' . $duration . ' days');
    $currentDate = new \DateTime();
    $difference = $currentDate->diff($finalDate);

    return $difference->days;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2014-02-14
    • 1970-01-01
    • 2018-10-12
    • 2012-06-03
    相关资源
    最近更新 更多