2012-08-22 36 views
0

執行檢查以查看用戶是否參加。如何將上下文變量is_attending傳遞給模板而不會在'is_attending': context['is_attending']上發生語法錯誤?該檢查基本上是爲造型div和whatnot。我究竟做錯了什麼?通過包含標籤傳遞上下文變量

模板:

{% for event in upcoming %} 
    {% registration %} 

    {% if is_attending %} 
     Registered! 
    {% else %} 
      Register button 
    {% endif %} 

    yadda yadda divs... 
{% endfor %} 

filters.py

@register.inclusion_tag('events/list.html', takes_context=True) 
def registration(context, event): 
    request = context['request'] 
    profile = Profile.objects.get(user=request.user) 
    attendees = [a.profile for a in Attendee.objects.filter(event=event)] 
    if profile in attendees: 
     'is_attending': context['is_attending'] 
     return is_attending 
    else: 
     return '' 

謝謝!

回答

4

'is_attending': context['is_attending']是無效的python。相反,它看起來像一部分字典。由於.inclusion_tag()代碼應該返回一個字典,也許你的意思,而不是以下:

if profile in attendees: 
    return {'is_attending': context['is_attending']} 
else: 
    return {'is_attending': ''} 

還要注意的是takes_context意味着你將採取上下文作爲參數。從howto on custom tags

如果指定在創建模板標籤takes_context,這個標籤就不需要參數,並且下面的Python功能將有一個參數 - 模板上下文當標籤被調用。

因此,你的標籤應該是:

{% registration %} 

和完整的方法可以直接從上下文采取event參數:

@register.inclusion_tag('events/list.html', takes_context=True) 
def registration(context): 
    request = context['request'] 
    event = context['event'] 
    profile = Profile.objects.get(user=request.user) 
    attendees = [a.profile for a in Attendee.objects.filter(event=event)] 
    if profile in attendees: 
     return {'is_attending': context['is_attending']} 
    else: 
     return {'is_attending': ''} 
+0

謝謝您的建議。但是,由於{%registration event%}'模板語法錯誤,我仍然無法傳遞'is_attending'。我沒有正確調用它嗎? – Modelesq

+0

@Modelesq:爲您更新了答案; 'take_context'包含標記方法只需要一個'context'參數。 –

+0

模板是事件列表。通過事件循環,必須進行檢查。由於這是通過特定事件中的與會者列表篩選的。我需要'{%registration event%}',否則它不會過濾'Attendee.objects.filter(event = event)'並執行檢查。 – Modelesq