2009-10-10 5 views
3

내 문제는 if 조건입니다.Django를 사용하여 특정 조건을 templatetag 생성하는 방법은 무엇입니까?

나는 그와 같은 일을하고 싶지만 어떻게해야 할지를 알 수 없다.

{% if restaurant.is_favorite_of(user) %} 
    <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" /> 
{% else %} 
    <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" /> 
{% endif %} 

는 즐겨 찾기 관리자, 나는 만든 :

{% is_favorite user resto %} 
    <img src="{{MEDIA_URL}}images/favorite_on.png" alt="This restaurant is one of your favorite (Click to undo)" /> 
{% else %} 
    <img src="{{MEDIA_URL}}images/favorite_off.png" alt="This restaurant is not one of your favorite (Click to add to your favorite)" /> 
{% endif %} 
:

def is_favorite(self, user, content_object): 
    """ 
    This method returns : 
     - True if content_object is favorite of user 
     - False if not 
    >>> user = User.objects.get(username="alice") 
    >>> fav_user = User.objects.get(username="bob") 
    >>> fav1 = Favorite.create_favorite(user, fav_user) 
    >>> Favorite.objects.is_favorite(user, fav_user) 
    True 
    >>> Favorite.objects.is_favorite(user, user) 
    False 
    >>> Favorite.objects.all().delete() 

    Above if we test if bob is favorite of alice it is true. 
    But alice is not favorite of alice. 
    """ 
    ct = ContentType.objects.get_for_model(type(content_object)) 
    try: 
     self.filter(user=user).filter(content_type = ct).get(object_id = content_object.id) 
     return True 
    except Favorite.DoesNotExist: 
     return False 

장고가이 좋아하는 일을 방법이 없습니다 템플릿에 있기 때문에, 내가처럼 말하고 templatetag을 할 수

하지만 어떻게해야합니까? 더 좋은 아이디어가 있습니까?

답변

11

가장 쉬운 방법은 필터를 만드는 것입니다.

@register.filter 
def is_favourite_of(object, user): 
    return Favourite.objects.is_favourite(user, object) 

템플릿 :

{% if restaurant|is_favourite_of:user %} 
+0
2

아마도 the inclusion tag을 사용할 수 있습니다.

그런 태그를 만듭니다

{% show_favorite_img user restaurant %} 

templatetags/user_extra.py을 :

@register.inclusion_tag('users/favorites.html') 
def show_favorite_img(user, restaurant): 
    return {'is_favorite': Favorite.objects.is_favorite(user, restaurant)} 
0

다른 모든 사용자가 값을 계산하고 당신이 사용할 수있는 변수에 붙어 태그 {어떤 % %의 EXPR}을 사용할 수 있습니다 실패하여 주형. 나는 디자이너들에게 그것에 대해 알리지 못하지만 때로는 당신의 머리에 서 있지 않고 ... 글쎄, 당신도 알다시피.

은 그게 전부가 좋은, 나는 우리가 만약 상태에서 필터를 사용할 수 몰랐

+0

나는 또한이 "spécial 태그"를 사용하지 않는 것을 선호합니다. – Natim

+0

전적으로 동의합니다. 몇 달 전에 나는 Django의 템플릿 템플릿 시스템에 대해 여러 가지 의견을 제시하지 못했다. 이것은 디자이너가 나쁜 일을하지 못하도록한다는 것이지만, 경험상 단순한 if/else가 프로그래머가 어쨌든 끝내는 것보다 더 복잡한 것입니다. 즉, 이와 같은 사소한 표현은 커스텀 태그 크 래프 트를 많이 생성합니다. 하나 또는 둘을하는 것은별로 중요하지 않으며, 그 후에는 매우 빨리 노화되기 시작합니다. –