Search code examples
djangodjango-templatesdjango-template-filters

How to use my simple custom django template tag with if statement?


I am trying to use my simple tag with if in django template.As far as i know assignment tag is removed from Django 2.0 . My template tag is:-

@register.simple_tag
def channelpostlike(postid,userid):
  print(userid)
  postresult=ChannelPost.objects.get(id=postid)
  if postresult.user_like.filter(id=userid).exists():
    return True
  else:
    return False

I want to use it like:-

{%if channelpostlike c.id request.user.id %}

Solution

  • Docs:

    assignment_tag Deprecated since version 1.9 simple_tag can now store results in a template variable and should be used instead.

    So you can use simple_tag like this:

    # You can access the result as something anywhere you like
    {% channelpostlike c.id request.user.id as something %}
    {% if something %}
        <p>Something ...</p>
    {% endif %}