3

カスタムユーザーの多対多のフィールド長の1つをカウントするdjangoテンプレートタグを作成しました。

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def unread_messages_count(context):
    user = context['request'].user
    return len(user.messages_unread.all())

テンプレート自体の中で、ゼロより大きい場合にのみユーザーに表示したいので、次のことを試しました。

{% ifnotequal unread_messages_count 0 %}
   some code...
{% endifnotequal %}

しかし、明らかにそれは機能しませんでした。'with'ステートメントでもありません:

{% with unread_messages_count as unread_count %}
    {% ifnotequal unread_count 0 %}
        some code...
    {% endifnotequal %}
{% endwith %}

変数が0より大きいことを確認し、大きい場合にのみ、ユーザーにコード(変数自体の数値を含む)を提示するにはどうすればよいですか。ありがとう。

4

2 に答える 2

9

最も簡単な方法は、割り当てタグを使用することです..

https://docs.djangoproject.com/en/dev/howto/custom-template-tags/#assignment-tags

@register.assignment_tag(takes_context=True)
def unread_messages_count(context):
    user = context['request'].user
    return len(user.messages_unread.all())

{% unread_messages_count as cnt %}
{% if cnt %}
   foo
{% endif %}
于 2013-02-08T07:21:29.037 に答える
2

djangoカスタムフィルターを使用できますhttps://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

def unread_messages_count(user_id):
  # x = unread_count   ## you have the user_id
  return x

とテンプレートで

{% if request.user.id|unread_messages_count > 0 %}
  some code...
{% endif %}
于 2013-02-08T13:05:13.100 に答える