如何在trick中设置if子句



我有这两个函数:

function is_expired($object) {
if (new DateTime('NOW') > $object) {
return true;
} else {
return false;
}
}
function is_not_started($object) {
if (new DateTime('NOW') < $object) {
return false;
} else {
return true;
}
}

$object是从数据库中提取的Datetime对象。我还注册了功能作为树枝过滤器。

对于一个投票系统,我有两个字段start_date和expiry_date,我想看看它是否没有过期,但已经开始了。

在树枝上我有:

{% if (category.endVote|is_expired == false) or (category.startVote|is_not_started == true) %}
<td><a href="voting.php?id={{ category.id }}">{{ category.categoryName|e }}</a></td>
{% else %}
<td>{{ category.categoryName|e }}</td>
{% endif %}

我的意思是,我只想看到categoryName作为链接,如果它已经启动并且没有过期。但它并没有像预期的那样起作用。我在if子句中做错了什么?

这是我的建议。

function can_vote($object) {
$now = new DateTime('now');
return $object->getEndVote() < $now && $object->getStartVote() > $now;
}
{% if category|can_vote is same as(true) %}
<td><a href="voting.php?id={{ category.id }}">{{ category.categoryName|e }}</a></td>
{% else %}
<td>{{ category.categoryName|e }}</td>
{% endif %}

不要使用两个单独的函数,而是将它们合并为一个函数并传入整个类别对象。同样在树枝部分,我建议使用更严格的方程,而不是"=="我的代码中的一个等同于"===&";。注意getEndVote((和getStartVote(((getter方法,如果您使用公共属性,请更改它们以反映正确的名称。

如果您希望最终使用两个独立的方法,提取该功能并不困难,但我认为这是一个更好的解决方案。

最新更新