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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…