da5a85bc73be4b44471e80dee44d60562cb89110
[wolnelektury.git] / src / search / templatetags / search_tags.py
1 # -*- coding: utf-8 -*-
2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 #
5 # import feedparser
6 # import datetime
7
8 from django import template
9 # from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
10 # from django.db.models import Q
11 # from django.utils.translation import ugettext as _
12 from catalogue.models import Book
13 import re
14 # from catalogue.forms import SearchForm
15 # from catalogue.utils import split_tags
16
17
18 register = template.Library()
19
20
21 @register.inclusion_tag('catalogue/book_searched.html', takes_context=True)
22 def book_searched(context, result):
23     book = Book.objects.get(pk=result.book_id)
24
25     # We don't need hits which lead to sections but do not have
26     # snippets.
27     hits = filter(lambda (idx, h):
28                   result.snippets[idx] is not None or ('fragment' in h and h['themes_hit']),
29                   enumerate(result.hits))
30     # print "[tmpl: from %d hits selected %d]" % (len(result.hits), len(hits))
31
32     for (idx, hit) in hits:
33         # currently we generate one snipper per hit though.
34         if len(result.snippets) <= idx:
35             break
36         if result.snippets[idx] is None:
37             continue
38         snip = result.snippets[idx]
39         # fix some formattting
40         snip = re.sub(r"[ \t\n]*\n[ \t\n]*", u"\n", snip)
41         snip = re.sub(r"(^[ \t\n]+|[ \t\n]+$)", u"", snip)
42
43         snip = snip.replace("\n", "<br />").replace('---', '&mdash;')
44         hit['snippet'] = snip
45
46     return {
47         'request': context['request'],
48         'book': book,
49         'hits':  zip(*hits)[1] if hits else []
50     }