如何使用Django创建特定的if条件模板标签?

时间:2009-10-10 01:53:40

标签: python django django-templates favorites

我的问题是if条件。

我想这样的事情,但无法弄清楚如何去做。

{% 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 %}

在收藏夹经理中,我创建了:

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

因为在Django模板中没有办法这样做,我可以做一个像这样的模板标签:

{% 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 %}
但是怎么做呢? 你有更好的主意吗?

3 个答案:

答案 0 :(得分:11)

最简单的方法是创建过滤器。

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

并在模板中:

{% if restaurant|is_favourite_of:user %}

答案 1 :(得分: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)}

答案 2 :(得分:0)

当所有其他方法都失败时,您可以使用{%expr whatever%}标记来计算值并将其粘贴到您可以在模板中使用的变量中。我不会让设计师知道它,但有时候它是唯一不起作用的东西......好吧,你知道。

请参阅http://www.djangosnippets.org/snippets/9/