我从数据库中获取一个数字(比方说,10
),我想在if/else
语句中使用它。请注意,我的变量可能等于0或null。
我的变量是item.getRate.getRate
。我在这样的模板中显示它:
{{item.getRate.getRate |默认('0')}}
我尝试通过
尝试执行if
语句
{%if item.getRate.getRate == 1%} {%endif%}
但它不起作用。
它在循环中运行,其中一个项目为空getRate
。这可能是问题吗?如果是的话 - 我该如何避免呢?
答案 0 :(得分:4)
您可以将两种测试结合起来,使您的代码易于阅读。
{% if item.getRate.getRate is defined and item.getRate.getRate == 1 %}
checked="checked"
{% endif %}
答案 1 :(得分:1)
我只需检查变量是否存在;)
{%if item.getRate.getRate定义为%} {%if item.getRate.getRate == 1%} checked =“checked”{%endif%} {%endif%}
有点长,但有效。谁有更好的主意?因为它会很棒,现在它有点难看:))
答案 2 :(得分:0)
假设getRate具有非零值,则此布尔值指示需要非空值,如您的示例所示:
{% if not(not(item.getRate.getRate)) %}
checked="checked"
{% endif %}