moviewyrm/fedireads/templatetags/fr_display.py

76 lines
2.1 KiB
Python
Raw Normal View History

2020-01-29 23:10:32 +00:00
''' template filters '''
from django import template
2020-02-21 23:39:25 +00:00
from fedireads import models
2020-01-29 23:10:32 +00:00
register = template.Library()
@register.filter(name='dict_key')
def dict_key(d, k):
'''Returns the given key from a dictionary.'''
return d.get(k) or 0
@register.filter(name='stars')
def stars(number):
''' turn integers into stars '''
2020-01-29 23:32:43 +00:00
try:
number = int(number)
except (ValueError, TypeError):
2020-01-29 23:32:43 +00:00
number = 0
2020-01-29 23:10:32 +00:00
return ('' * number) + '' * (5 - number)
2020-01-29 23:32:43 +00:00
@register.filter(name='description')
def description_format(description):
''' handle the various OL description formats '''
if isinstance(description, dict) and 'value' in description:
description = description['value']
if '----------' in description:
description = description.split('----------')[0]
return description.strip()
2020-02-11 06:40:20 +00:00
@register.filter(name='author_bio')
def bio_format(bio):
''' clean up OL author bios '''
if isinstance(bio, dict) and 'value' in bio:
bio = bio['value']
2020-02-11 06:40:20 +00:00
bio = bio.split('\n')
return bio[0].strip()
2020-02-21 23:39:25 +00:00
@register.simple_tag(takes_context=True)
def shelve_button_identifier(context, book):
''' check what shelf a user has a book on, if any '''
try:
shelf = models.ShelfBook.objects.get(
shelf__user=context['user'],
book=book
)
except models.ShelfBook.DoesNotExist:
return 'to-read'
identifier = shelf.shelf.identifier
if identifier == 'to-read':
return 'reading'
elif identifier == 'reading':
return 'read'
return 'to-read'
@register.simple_tag(takes_context=True)
def shelve_button_text(context, book):
''' check what shelf a user has a book on, if any '''
try:
shelf = models.ShelfBook.objects.get(
shelf__user=context['user'],
book=book
)
except models.ShelfBook.DoesNotExist:
return 'Want to read'
identifier = shelf.shelf.identifier
if identifier == 'Start reading':
return 'reading'
elif identifier == 'reading':
return 'I\'m done!'
return 'Want to read'