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
151 views
in Technique[技术] by (71.8m points)

html - django template for loop and if statements to separate search results

I want to separate my search results by category. Here is my search_results.html:

{% extends "base.html" %}
{% load static %}
{% load search_extras %}
{% block content %}

    <h2>Search results for <b>'{{ query }}' </b> (appearing {% if count == 1 %} once): {% else %}{{ count }} times):{% endif %} </h2>
    <p> <i>Only unique results are shown </i></p>

    <h3>Word results</h3>    
{% for query in object_list %}
{% if query.target_word or query.source_word %}
{{ forloop.counter }}
{% with query|class_name as class %}
{% if class == 'Word' %}
        {{query}}
{% endif %}
{% endwith %}
{% endif %}
{% empty %}
    <p>No search results match your query.</p>    
{% endfor %}
    <h3>Song results</h3>
{% for query in object_list %}
{% if query.title or query.artist %}
{{ forloop.counter }}
{% with query|class_name as class %}
{% if class == 'Song' %}  
    {{query}}    
{% endif %}
{% endwith %}
{% endif %}
{% empty %}
<p>No search results match your query.</p>
{% endfor %}    

{% endblock %}

And this gives the required output if there are results for both categories, e.g.:

Search results for 'x' (appearing 4 times):
Only unique results are shown

Word results
1 word1
2 word2

Song results
3 song1
4 song2

But say there are no word results, then I don't want the Word results heading to appear. And it seems that the only way to achieve that would be to move the heading after {% if query.target_word or query.source_word %}. But then if there are results, the heading appears for every query. So it seems a bit circular. Is there any way to achieve the output I want?

question from:https://stackoverflow.com/questions/65557581/django-template-for-loop-and-if-statements-to-separate-search-results

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

1 Reply

0 votes
by (71.8m points)
Waitting for answers

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

...