Add Book.ancestor m2m.
[wolnelektury.git] / apps / 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 from catalogue.templatetags.catalogue_tags import book_short
14 import re
15 # from catalogue.forms import SearchForm
16 # from catalogue.utils import split_tags
17
18
19 register = template.Library()
20
21
22 @register.inclusion_tag('catalogue/book_searched.html', takes_context=True)
23 def book_searched(context, result):
24     book = Book.objects.get(pk=result.book_id)
25
26     # snippets = []
27     # for hit in result.hits:
28     #     if hit['snippets']:
29     #         snippets.append(hit['snippets'])
30     #     elif hit['fragment']:
31     #         snippets.append(hit['fragment'].short_text)
32
33     # We don't need hits which lead to sections but do not have
34     # snippets.
35     hits = filter(lambda (idx, h):
36                   result.snippets[idx] is not None
37                   or 'fragment' in h, enumerate(result.hits))
38         #    print "[tmpl: from %d hits selected %d]" % (len(result.hits), len(hits))
39
40     for (idx, hit) in hits:
41         # currently we generate one snipper per hit though.
42         if result.snippets[idx] is None:
43             continue
44         snip = result.snippets[idx]
45         # fix some formattting
46         snip = re.subn(r"(^[ \t\n]+|[ \t\n]+$)", u"",
47                               re.subn(r"[ \t\n]*\n[ \t\n]*", u"\n", snip)[0])[0]
48
49         snip = snip.replace("\n", "<br />").replace('---', '&mdash;')
50         hit['snippet'] = snip
51
52     ctx = book_short(context, book)
53     ctx['hits'] = hits and zip(*hits)[1] or []
54     return ctx