首页 > 解决方案 > 如何将我的简单自定义 django 模板标签与 if 语句一起使用?

问题描述

我正在尝试在 django 模板中使用我的简单标签。据我所知,赋值标签已从 Django 2.0 中删除。我的模板标签是:-

@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

我想像这样使用它:-

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

标签: djangodjango-templatesdjango-template-filters

解决方案


文件:

assignment_tag 自 1.9 版以来已弃用 simple_tag 现在可以将结果存储在模板变量中,应改为使用。

所以你可以simple_tag这样使用:

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

推荐阅读