英文:
Django checking if message.tags contains string always return false
问题
在我的视图中,我已经设置了extra_tags
,但是当我在模板中检查目标标签时,条件始终评估为false。
视图:
messages.success(request, "success")
messages.info(request, "you can undo this", extra_tags="undo")
模板:
{% for message in messages %}
{{ message.extra_tags }}
<li>
{% if 'undo' in message.extra_tags %}
this has undo in tags
{% else %}
{{ message }}
{% endif %}
</li>
{% endfor %}
这导致生成以下HTML:
* success
* you can undo this
这是我期望的:
* success
* this has undo in tags
(1)
英文:
I have set extra_tags
in my view, but when I check for the target tag in my template, the condition always evaluates to false.
View:
messages.success(request, "success")
messages.info(request, "you can undo this", extra_tags="undo")
Template:
{% for message in messages %}
{{ message.extra_tags }}
<li>
{% if 'undo' in messages.extra_tags %}
this has undo in tags
{% else %}
{{ message }}
{% endif %}
</li>
{% endfor %}
This result in this HTML:
* success
* you can undo this
This is what I expect
* success
* this has undo in tags
(1) I have confirmed that the "undo" tag is output from {{ message.extra_tags }}
(2) I have tried messages.tags
instead of messages.extra_tags
but neither method reaches the true branch in the if condition.
答案1
得分: 2
你的条件似乎不正确。因为你正在迭代来自消息框架的每条消息,你需要检查message
上的extra_tags
而不是messages
。
所以,你的模板应该如下所示:
{% for message in messages %}
{{ message.extra_tags }}
<li>
{% if 'undo' in message.extra_tags %}
这个标签中有“undo”
{% else %}
{{ message }}
{% endif %}
</li>
{% endfor %}
请注意,在这里,我们正在检查当前正在迭代的message
对象。
英文:
Your condition seems wrong. Since you're iterating over each message coming from the messages framework, you'll have to check the extra_tags
on the message
and not the messages
.
So, your template will become:
{% for message in messages %}
{{ message.extra_tags }}
<li>
{% if 'undo' in message.extra_tags %}
this has undo in tags
{% else %}
{{ message }}
{% endif %}
</li>
{% endfor %}
Notice here, that we're checking the current message
object that is being iterated on.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论