pythondjangodjango-templatesdjango-tagging

Django - use template tags in if statement


I saw similar questions but none of them solved my problem .

I have a simple template tag like this :

@register.simple_tag
def liked_by_user(post_id, user):
    try:
        PostModel.objects.get(pk=post_id).like_set.get(user=user)
        return True
    except:
        return False

and i want to use this in an if statement like this :

{% if liked_by_user post.pk request.user %}
        doing somethin...
    {% else %}
        doing somethin...
{% endif %}

what can i do ?


Solution

  • I would set out your template something like this:

    {% liked_by_user "post_id" "request.user" as liked_by_user_flag %}
    
    {% if liked_by_user_flag %} 
       doing somethin...
    {% else %} 
       doing somethin...
    {% endif %}
    

    However, this intuitively doesn't feel like a template tag sort of situation...but I'm not 100% sure of your use case just yet from your question.