1. RJ Ryan
  2. sorl-thumbnail

Commits

smil...@18c32c52-eb3f-0410-93bd-f15eff1430f4  committed c6cd0d9

Make a new funky thumbnail tag, renaming the library to "thumbnails" so
it doesn't clash with the app name

  • Participants
  • Parent commits dd12bf1
  • Branches smiley-refactor

Comments (0)

Files changed (2)

File thumbnail/templatetags/thumbnail.py

  • Ignore whitespace
-import re, os
-from django.template import Library
-from sorl.thumbnail.main import Thumbnail, METHOD_LIST
-from django.conf import settings
-
-register = Library()
-
-@register.filter
-def thumbnail_url(filename, arg=""):
-    try:
-        thumbnail = get_thumbnail(filename, arg)
-    except:
-        if hasattr(settings, 'THUMBNAIL_DEBUG') and settings.THUMBNAIL_DEBUG:
-            raise
-        else:
-            return ""
-    
-    return thumbnail.get_url()
-
-
-def get_thumbnail(filename, arg=""):
-
-    kwargs  = {\
-        'prefix': '',
-        'subdir': '_thumbs',
-        'quality': 85,
-        'filename_encoding': 'utf-8',
-    }
-    for a in kwargs.keys():
-        if hasattr(settings, 'THUMBNAIL_%s' % a.upper()):
-            kwargs.update({a: getattr(settings, 'THUMBNAIL_%s' % a.upper())})
-    kwargs.update({'filename': filename, size: (80,80)})
-     
-    arg_list = arg.split()
-    for m in METHOD_LIST:
-        kwargs.update({m: m in arg_list})
-    quality_pat = re.compile(r'q(\d+)')
-    m = quality_pat.search(arg)
-    if m:
-        quality = int(m.group(1))
-        if quality > 0 and quality <= 100:
-            kwargs.update(quality=quality)
-    size_pat = re.compile(r'(\d+)x(\d+)')
-    m = size_pat.search(arg)
-    if m:
-        kwargs.update(size=(int(m.group(1)), int(m.group(2))))
-
-    return Thumbnail(**kwargs)

File thumbnail/templatetags/thumbnails.py

View file
  • Ignore whitespace
+import re
+import os
+
+from django import template
+from django.conf import settings
+
+from thumbnail.main import DjangoThumbnail
+from thumbnail.base import OPTIONS
+
+register = template.Library()
+
+class ThumbnailNode(template.Node):
+    def __init__(self, source_var, context_name=None, opts=None, debug=False,
+                 thumbnail_class=DjangoThumbnail):
+        self.context_name = context_name
+        self.source_var = template.Variable(source_var)
+        self.opts = opts or {}
+        self.debug = debug
+        self.thumbnail_class = thumbnail_class
+    def render(self, context):
+        source_path = self.source_var.resolve(context)
+        try:
+            thumbnail = self.thumbnail_class(source_path, **self.opts)
+        except:
+            if self.debug:
+                raise
+            return ''
+        if not self.context_name:
+            return thumbnail
+        context[self.context_name] = thumbnail
+        return ''
+
+@register.tag
+def thumbnail(parser, token):
+    return get_thumbnail_node(token)
+
+@register.tag
+def thumbnail_debug(parser, token):
+    return get_thumbnail_node(token, debug=True)
+
+re_quality = re.compile(r'q(\d{1,3})$')
+re_dimensions = re.compile(r'(\d+)x(\d+)$')
+def get_thumbnail_node(token, debug=False, thumbnail_class=DjangoThumbnail):
+    """
+    To just output the url to the thumbnail::
+
+        {% thumbnail image_path 80x80 %}
+
+    After the image path and dimensions, you can put any options::
+
+        {% thumbnail image_path 80x80 q95 crop %}
+
+    To put the DjangoThumbnail class on the context instead of just rendering
+    the url, finish the tag with "as [context_var_name]"::
+
+        {% thumbnail image_path 80x80 as thumb %}
+        {{ thumb.thumbnail.size.0 }} x {{ thumb.thumbnail.size.1 }}
+    """
+    args = token.split_contents()
+    if len(args) < 3:
+        raise template.TemplateSyntaxError("'%s' tag requires at least two arguments" % args[0])
+    source_var = args[1]
+    opts = {}
+
+    # Get the dimensions
+    dimensions = re_dimensions.match(args[2])
+    if not dimensions:
+        raise template.TemplateSyntaxError("'%s' tag received invalid dimensions - expected something like 80x80 but got '%s'" % args[2])
+    opts['size'] = [int(d) for d in dimensions.groups()]
+
+    # Check to see if we're setting to a context variable.
+    if len(args) >= 5 and args[-2] == 'as':
+        context_name = args[-1]
+        args = args[:-2]
+    else:
+        context_name = None
+
+    # Check the rest of the options
+    for arg in args[3:]:
+        if not 'quality' in opts:
+            quality = re_quality.match(arg)
+            if quality:
+                opts['quality'] = int(q.group(1))
+                continue
+        if arg not in OPTIONS:
+            raise template.TemplateSyntaxError("'%s' tag received invalid argument: '%s'" % arg)
+        opts[str(arg)] = True
+
+    return ThumbnailNode(source_var=source_var, context_name=context_name,
+                         opts=opts, debug=debug, thumbnail_class=thumbnail_class)