Permalink
Browse files

Adding in some template helpers for the search results.

  • Loading branch information...
1 parent ae0025c commit 11d559740ab5374a04d1f862d98afe637ce1616d @etianen committed May 8, 2012
@@ -0,0 +1,8 @@
+<article>
+ <h1>
+ <a href="{{result.url}}">{{result.title}}</a>
+ </h1>
+ {% if result.description %}
+ {{result.description|linebreaks}}
+ {% endif %}
+</article>
@@ -0,0 +1,10 @@
+{% load watson %}
+{% if search_results %}
+ <ul class="search-results">
+ {% for search_result in search_results %}
+ <li>
+ {% search_result_item search_result %}
+ </li>
+ {% endfor %}
+ </ul>
+{% endif %}
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!DOCTYPE html>{% load watson %}
<html>
<head>
<meta charset="utf-8">
@@ -8,24 +8,14 @@
<body>
<h1>Search results{% if query %} for &ldquo;{{query}}&rdquo;{% endif %}</h1>
{% if search_results %}
- <ul>
- {% for result in search_results %}
- <li>
- <article>
- <h1>
- {% if result.url %}<a href="{{result.url}}">{% endif %}
- {{result.title}}
- {% if result.url %}</a>{% endif %}
- </h1>
- {% if result.description %}
- <p>{{result.description}}</p>
- {% endif %}
- </article>
- </li>
- {% endfor %}
- </ul>
+ {% search_results search_results %}
{% else %}
- <p><em>There are no results to display.</em></p>
+ {% if query %}
+ <p><em>There are no results to display.</em></p>
+ <p><em>Try entering a less specific search term.</em></p>
+ {% else %}
+ <p><em>Please enter a query in the search form.</em></p>
+ {% endif %}
{% endif %}
</body>
</html>
@@ -0,0 +1 @@
+"""Template tags used by watson search."""
@@ -0,0 +1,48 @@
+"""Template helpers used by watsons search."""
+
+from django import template
+
+
+register = template.Library()
+
+
+@register.simple_tag(takes_context=True)
+def search_results(context, search_results):
+ """Renders a list of search results."""
+ # Prefetch related for speed, if available.
+ if hasattr(search_results, "prefetch_related"):
+ search_results = search_results.prefetch_related("object")
+ # Render the template.
+ context.push()
+ try:
+ context.update({
+ "search_results": search_results,
+ "query": context["query"],
+ })
+ return template.loader.render_to_string("watson/includes/search_results.html", context)
+ finally:
+ context.pop()
+
+
+@register.simple_tag(takes_context=True)
+def search_result_item(context, search_result):
+ obj = search_result.object
+ params = {
+ "app_label": obj._meta.app_label,
+ "model_name": obj.__class__.__name__.lower(),
+ }
+ # Render the template.
+ context.push()
+ try:
+ context.update({
+ "obj": obj,
+ "result": search_result,
+ "query": context["query"],
+ })
+ return template.loader.render_to_string((
+ "watson/includes/search_result_{app_label}_{model_name}.html".format(**params),
+ "watson/includes/search_result_{app_label}.html".format(**params),
+ "watson/includes/search_result_item.html",
+ ), context)
+ finally:
+ context.pop()

0 comments on commit 11d5597

Please sign in to comment.