Source

gnocchi-gallery / gnocchi / gallery / templatetags / gallery.py

Full commit
from django import template
from django.db.models import Q
from django.utils.html import escape

from gnocchi.gallery.models import Gallery, ThumbnailConfig

import re
from easy_thumbnails.files import get_thumbnailer

register = template.Library()

@register.simple_tag(takes_context=True)
def load_gallery(context, gallery, varname='gallery'):
    try:
        context[varname] = Gallery.objects.get(Q(name=gallery)|Q(slug=gallery))
    except Gallery.DoesNotExist:
        context[varname] = None
    return ''


RE_SIZE = re.compile(r'(\d+)x(\d+)$')

@register.filter
def config_thumbnail(source, name):
    '''Turns an image field or image path into a URL to a thumbnail, made using
    the named config.
    '''

    try:
        config = ThumbnailConfig.objects.get(name=name)
    except ThumbnailConfig.DoesNotExist:
        return ''
    config._load_cache()
    opts = config._attributes
    if 'size' in opts:
        m = RE_SIZE.match(opts['size'])
        if m:
            opts['size'] = (int(m.group(1)), int(m.group(2)))
        else:
            return ''
    thumbnail = get_thumbnailer(source).get_thumbnail(config._attributes)
    return escape(thumbnail.url)