与 Twig Symfony 4 的整数比较

Integer comparison with Twig Symfony 4

我试图在 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;
    }

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

在我的 Twig 上我有:

{% 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,第二个条件为 + 随机值。

我做错了什么?

这应该有效

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;
}