Fundraising in PDF.
[wolnelektury.git] / src / chunks / templatetags / chunks.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from django import template
5 from django.core.cache import cache
6 from django.utils.safestring import mark_safe
7 from django.utils.translation import get_language
8 from ..models import Chunk, Attachment
9
10
11 register = template.Library()
12
13
14 @register.simple_tag(takes_context=True)
15 def chunk(context, key, cache_time=0):
16     try:
17         cache_key = 'chunk:%s:%s' % (key, get_language())
18         c = cache.get(cache_key)
19         if c is None:
20             c = Chunk.objects.get(key=key)
21             cache.set(cache_key, c, int(cache_time))
22         content = c.content
23     except Chunk.DoesNotExist:
24         n = Chunk(key=key)
25         n.save()
26         content = ''
27
28     if 'request' in context and context['request'].user.is_staff:
29         content = f'<span data-edit="chunks/chunk/{key}"></span>' + content
30
31     return mark_safe(content)
32
33
34 @register.simple_tag
35 def attachment(key, cache_time=0):
36     try:
37         cache_key = 'attachment_' + key
38         c = cache.get(cache_key)
39         if c is None:
40             c = Attachment.objects.get(key=key)
41             cache.set(cache_key, c, int(cache_time))
42         return c.attachment.url
43     except Attachment.DoesNotExist:
44         return ''