add pictures in search
[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 from django import template
6 import re
7
8 register = template.Library()
9
10
11 @register.inclusion_tag('catalogue/book_searched.html', takes_context=True)
12 def book_searched(context, result):
13     # We don't need hits which lead to sections but do not have
14     # snippets.
15     hits = filter(lambda (idx, h):
16                   result.snippets[idx] is not None or ('fragment' in h and h['themes_hit']),
17                   enumerate(result.hits))
18     # print "[tmpl: from %d hits selected %d]" % (len(result.hits), len(hits))
19
20     for (idx, hit) in hits:
21         # currently we generate one snipper per hit though.
22         if len(result.snippets) <= idx:
23             break
24         if result.snippets[idx] is None:
25             continue
26         snip = result.snippets[idx]
27         # fix some formattting
28         snip = re.sub(r"[ \t\n]*\n[ \t\n]*", u"\n", snip)
29         snip = re.sub(r"(^[ \t\n]+|[ \t\n]+$)", u"", snip)
30
31         snip = snip.replace("\n", "<br />").replace('---', '&mdash;')
32         hit['snippet'] = snip
33
34     return {
35         'request': context['request'],
36         'book': result.book,
37         'hits':  zip(*hits)[1] if hits else []
38     }