2013-04-29 71 views
4

如何使條件語句脫離Django模板標籤Django模板標籤有條件

from django import template 
from django.contrib.auth.models import User, Group 

register = template.Library() 

@register.simple_tag 
def is_designer(user_id): 
    try: 
     group = Group.objects.get(
      name = "Designer", 
      user = user_id 
     ) 
     return True 
    except Group.DoesNotExist: 
     return False 

這出現在我的模板,這是正確的真或假:

{% is_designer user.id %} 

然而,這些給我一個錯誤「未使用‘user.id’在if語句的結束」:

{%如果is_designer user.id ==真%}是{%ENDIF%}

{%如果is_desig NER user.id%}是{%ENDIF%}

回答

9

如果您作出爲assignment tag,你可以不喜歡

{% is_designer user.id as is_user_designer %} 

{% if is_user_designer == True %} Yes {% endif %} 

{% if is_user_designer %} Yes {% endif %} 
+3

謝謝這有效,但我用過濾器代替:'{%if user | is_maker%} YES {%endif%}' – JREAM 2013-04-29 19:08:36

1

這個怎麼樣:

{% is_designer user.id as is_user_designer %} 
{{ is_user_designer|yesno:"Yes," }}