[英]Django templatetag without value and object to return True or False
[英]Django templatetag return True or False
我正在Django中覆蓋admintemplate的index.html。 我想在側邊欄上添加一個額外的字段,僅在條件為true時才顯示。
這是m index.html的重要部分:
{% block sidebar %}
<div id="content-related">
{% if action_needed %}
<div class="my-module">
<h2>Foobar</h2>
<p>Display this over the sidebar</p>
</div>
{% endif %}
... Sidebarstuff...
{% endblock %}
這是我的模板標簽:
@register.simple_tag
def action_needed():
if some_conditon:
return True
else:
return False
問題是my-module一直顯示。 在另一個線程中,我讀到了有關使用過濾器而不是templatetag的信息,但是Django文檔說,過濾器至少需要1個參數。 但是我只是想要一個正確/錯誤的回報。
最好的方法是什么?
編輯:這是更多的代碼,向您展示我到底在做什么:我有一個模型帳戶,如果一個帳戶過期,則該模型帳戶具有一個DateTimeField expiration_date來存儲。
exp = Account.objects.filter(expiration_date__lte = timezone.now())
if len(exp) == 0:
return False
else:
return True
Edit2:我解決了它,但我不知道這是否是一種非常優雅的方法。 由於我沒有足夠的聲譽來回答自己的問題,因此我需要在此處分享我的解決方案:
如果條件為True,則將my-module內的my-module放入HTML代碼,並返回它:
@register.simple_tag
def action_needed():
if some_conditon:
return '<div class="my-module"><h2>Foobar</h2><p>Display this over the sidebar</p></div>'
else:
return ''
現在在模板中,我只是調用
{% action_needed %}
您的第一種方法( action_needed
標簽返回boolean + if
標簽)不起作用,導致模板標簽無法用作另一方法的“參數”,因此您的{% if action_needed %}
嘗試在上下文中解析名為action_needed
的變量 。
如果測試(“ some_condition”)取決於當前上下文中可用的某個對象,則可以使用應用於該對象的自定義過濾器,即:
@register.filter
def action_needed(obj):
return some_test_on(obj)
{% if obj|action_needed %}
whatever
{% endif %}
否則,您要么必須編寫一個在上下文中設置該標志的分配標簽,然后測試該標志,要么像您最終所做的那樣,編寫一個標簽進行測試並返回相應的html代碼段。
只是作為旁注-這:
exp = Account.objects.filter(expiration_date__lte = timezone.now())
if len(exp) == 0:
return False
else:
return True
是編寫此代碼的一種復雜方法:
return len(Account.objects.filter(expiration_date__lte=timezone.now())) > 0
這是這樣寫的低效方式:
return Account.objects.filter(expiration_date__lte=timezone.now()).exists()
您可以創建一個自定義模板標記,以檢查是否滿足條件。 如果為true,則在標記之間呈現html。
{% block sidebar %}
<div id="content-related">
{% ifaction %}
<div class="my-module">
<h2>Foobar</h2>
<p>Display this over the sidebar</p>
</div>
{% endifaction %}
... Sidebarstuff...
{% endblock %}
您可以通過查看石像鬼的ifswitch標簽的代碼來了解它是如何完成的。
您可以在這里采取幾種方法。 一種想法是將some_condition
檢查作為上下文處理器,因此它會自動包含在所有模板中-盡管如果只希望將其放在一個模板中,這是過大的選擇。
更好的方法是使用包含標簽。 這樣, {% if action_needed %}
標簽中當前的代碼將在單獨的模板代碼段中,僅在條件為true時才包括在內。 或者,您可以使用分配標記在上下文中設置變量,然后在if
對其進行檢查。
(還請注意,您的代碼效率極低,因為它可能涉及獲取所有將來的Account
對象。 if exp.exists()
應該執行簡單的存在性檢查,則應該這樣做。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.