[英]complex condition in django template?
如何在 django 模板中執行此操作:
{% if li_status.profile_exists and (op1.conns|length > 0 or op2.conns|length > 0) %}
括號在此表達式中是非法的,我不確定沒有它們將如何評估表達式。
我更喜歡在一行中執行此操作,而不是使用嵌套的 if
正如danihp所說,通常沒有理由在模板中做這種事情。 在模板中應避免這種邏輯,這就是Django不提供這樣做的能力的原因。
您是否嘗試過類似的方法?
def your_view(request):
# Stuff
condition = li_status.profile_exists and (len(op1.conns) > 0 or len(op2.conns) > 0)
return render_to_response('your-template.html',
{
'condition': condition
},
RequestContext(request)
)
然后在您的模板中:
{% if condition %}
...
如果條件在循環中,並且對該查詢集中的項目屬性進行操作(根據 Ben Davis 的評論),那么該技術是運行循環並在將結果放入上下文之前對其進行修飾。 以下是執行此操作的多種方法之一:
# in the view somewhere
qs = MyObject.objects.all()
decorated = []
for item in qs:
item.field_that_does_not_exist_on_the_model = expensive(item)
decorated.append(item)
..然后你把decorated
放在上下文中,而不是qs
並像任何其他字段一樣使用 t :
{% for item in decorated %}
{% if item.field_that_does_not_exist_on_the_model %}
..
{% endif %}
{% endfor %}
這樣做的另一個好處是,如果它很慢,則可以對其進行優化。 將查詢集移交給模板后,您無法優化查詢集訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.