Skip to content

Commit 180e36a

Browse files
committed
Added docs on handling content-type specific output in results.
1 parent 0fabbdc commit 180e36a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

docs/best_practices.rst

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,67 @@ your ``SearchIndex`` as the HTML result.
133133
query for each type of model with ``load_all=True``.
134134

135135

136+
Content-Type Specific Templates
137+
===============================
138+
139+
Frequently, when displaying results, you'll want to customize the HTML output
140+
based on what model the result represents.
141+
142+
In practice, the best way to handle this is through the use of ``include``
143+
along with the data on the ``SearchResult``.
144+
145+
Your existing loop might look something like::
146+
147+
{% for result in page.object_list %}
148+
<p>
149+
<a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
150+
</p>
151+
{% empty %}
152+
<p>No results found.</p>
153+
{% endfor %}
154+
155+
An improved version might look like::
156+
157+
{% for result in page.object_list %}
158+
{% if result.content_type == "blog.post" %}
159+
{% include "search/includes/blog/post.html" %}
160+
{% endif %}
161+
{% if result.content_type == "media.photo" %}
162+
{% include "search/includes/media/photo.html" %}
163+
{% endif %}
164+
{% empty %}
165+
<p>No results found.</p>
166+
{% endfor %}
167+
168+
Those include files might look like::
169+
170+
# search/includes/blog/post.html
171+
<div class="post_result">
172+
<h3><a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a></h3>
173+
174+
<p>{{ result.object.tease }}</p>
175+
</div>
176+
177+
# search/includes/media/photo.html
178+
<div class="photo_result">
179+
<a href="{{ result.object.get_absolute_url }}">
180+
<img src="http://your.media.example.com/media/{{ result.object.photo.url }}"></a>
181+
<p>Taken By {{ result.object.taken_by }}</p>
182+
</div>
183+
184+
You can make this even better by standardizing on an includes layout, then
185+
writing a template tag or filter that generates the include filename. Usage
186+
might looks something like::
187+
188+
{% for result in page.object_list %}
189+
{% with result|search_include as fragment %}
190+
{% include fragment %}
191+
{% endwith %}
192+
{% empty %}
193+
<p>No results found.</p>
194+
{% endfor %}
195+
196+
136197
Real-Time Search
137198
================
138199

0 commit comments

Comments
 (0)