gnocchi-gallery / gnocchi_gallery / templatetags /

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

from gnocchi_gallery.models import Gallery, ThumbnailConfig
from gnocchi_tools.template import parse_args

import re
from easy_thumbnails.files import get_thumbnailer

register = template.Library()

class LoadGalleryNode(template.Node):
    def __init__(self, gallery, var): = gallery
        self.var = var

    def render(self, context):
        name =
        varname = self.var
        if not isinstance(varname, basestring):
            varname = varname.resolve(context)
            context[varname] = Gallery.objects.get(Q(name=name)|Q(slug=name))
        except Gallery.DoesNotExist:
            context[varname] = None
        return ''

def load_gallery(parser, token):
    args, kwargs, varname = parse_args(parser, token, 'gallery')
    if len(args) != 1 or kwargs:
        raise template.TemplateSyntaxError, \
            'load_gallery requires one position, and no keyword, argument.' % args[0]
    return LoadGalleryNode(args[0], varname)

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

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


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