Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

html - Django dynamically display a list but ignore some items

I am trying to show a list of groups on the sidebar on my html using Django. The first item will always be "all". so when I tranverse through all the groups/subreddits, I would first display "all" and then display the rest. however, when I display the rest and when it hits "all" again, instead of doing nothing, it seems to be printing a empty line because later when I display it in forms, I notice that I have a blank cell. I wonder how do I make sure that it just ignores "all" and goes on to display the next group without the empty space. Here is the code:

    <div class="post" id="title"><h4>Groups </h4></div>

    {% for sub in subreddits %}

        {% if sub.name == 'all' %}
            <div class="post"> <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a></div>
        {% endif %}

    {% endfor %}


    {% for sub in subreddits %}
        <div class="post">
            {% if sub.name != 'all' %}
                <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a>
            {% endif %}
        </div>
    {% endfor %}
question from:https://stackoverflow.com/questions/65946846/django-dynamically-display-a-list-but-ignore-some-items

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem

Think about what will get rendered when sub.name == 'all' - the <div> is currently outside the if tag, so was getting displayed regardless. You'll get this:

<div class="post">

</div>

This is probably why you're getting an extra line.

The solution

Move the <div> inside your if tag:

    {% for sub in subreddits %}
        {% if sub.name != 'all' %}
            <div class="post">
                <a href="{% url 'sub_detail' pk=sub.pk %}">{{ sub.name }}</a> 
            </div>
        {% endif %}
    {% endfor %}

This way when sub.name == 'all', nothing is rendered at all.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...