python Django 模板:比较 IF 语句中的字典长度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/762118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:49:04  来源:igfitidea点击:

Django Template: Comparing Dictionary Length in IF Statement

pythondjango

提问by Eldila

I am trying to compare the length of a dictionary inside a django template

我正在尝试比较 django 模板中字典的长度

For example, I would like to know the correct syntax to do the following:

例如,我想知道执行以下操作的正确语法:

    {% if error_messages %}
        <div class="error">
            {% if length(error_messages) > 1 %}
                Please fix the following errors:
                <div class="erroritem">
                    {% for key, value in error_messages.items %}
                        <br>{{ value }}
                    {% endfor %}
                </div>

            {% else %}
                    {% for key, value in error_messages.items %}
                        {{ value }}
                    {% endfor %}
            {% endif %}
        </div>
    {% endif %}

回答by Paolo Bergantino

You could do this, using the lengthfilter and the ifequaltag:

你可以使用长度过滤器和ifequal标签来做到这一点:

{% if error_messages %}
    <div class="error">
        {% ifequal error_messages|length 1 %}
            error_messages[0]
        {% else %}
            Please fix the following errors:
            <div class="erroritem">
            {% for key, value in error_messages.items %}
                <br>{{ value }}
            {% endfor %}
            </div>
        {% endifequal %}
    </div>
{% endif %}

Anything else will have to go down the path of custom tags and filters.

其他任何事情都必须遵循自定义标签和过滤器的路径。

回答by gbozee

You can actually use both the iftag and the lengthfilter

您实际上可以同时使用if标签和 length过滤器

{% if page_detail.page_content|length > 2 %}
<strong><a class="see-more" href="#" data-prevent-default="">
Learn More</a></strong>{% endif %}

NBEnsure no spaces between the dictionary/object and the lengthfilter when used in the iftag so as not to throw an exception.

注意lengthif标签中使用时, 确保字典/对象和过滤器之间没有空格,以免引发异常。

回答by zack

use the smart_if template tag:

使用 smart_if 模板标签:

http://www.djangosnippets.org/snippets/1350/

http://www.djangosnippets.org/snippets/1350/

its super cool :)

它超级酷:)

can do all the obvious stuff like:

可以做所有显而易见的事情,比如:

{% if articles|length >= 5 %}...{% endif %}

{% if 文章|长度 >= 5 %}...{% endif %}

{% if "ifnotequal tag" != "beautiful" %}...{% endif %}

{% if "ifnotequal tag" != "beautiful" %}...{% endif %}