3
3
from django .utils .encoding import force_str
4
4
from django .utils .html import escape
5
5
from django .utils .safestring import mark_safe
6
+ from django .conf import settings
6
7
7
8
from ..cachefiles import ImageCacheFile
8
9
from ..registry import generator_registry
13
14
ASSIGNMENT_DELIMETER = 'as'
14
15
HTML_ATTRS_DELIMITER = '--'
15
16
DEFAULT_THUMBNAIL_GENERATOR = 'imagekit:thumbnail'
17
+ default_thumbnail_srcset_scales = getattr (settings , 'IMAGEKIT_DEFAULT_THUMBNAIL_SRCSET_SCALES' , None )
16
18
17
19
18
20
def get_cachefile (context , generator_id , generator_kwargs , source = None ):
@@ -126,11 +128,27 @@ def render(self, context):
126
128
# recursion errors when anchor is set to a SafeString instance.
127
129
# This converts the SafeString into a str instance.
128
130
kwargs ['anchor' ] = kwargs ['anchor' ][:]
131
+ srcset_scales = default_thumbnail_srcset_scales
132
+ if "srcset" in kwargs :
133
+ if kwargs ['srcset' ] is not None :
134
+ srcset_scales = list (map (float , kwargs ['srcset' ].split ()))
135
+ else :
136
+ srcset_scales = None
137
+ kwargs .pop ("srcset" )
129
138
if kwargs .get ('format' ):
130
139
kwargs ['format' ] = kwargs ['format' ][:]
131
140
generator = generator_registry .get (generator_id , ** kwargs )
132
141
133
142
file = ImageCacheFile (generator )
143
+ srcset = []
144
+ if srcset_scales :
145
+ for scale in srcset_scales :
146
+ scaled_kwargs = dict (kwargs )
147
+ if scaled_kwargs .get ("height" ):
148
+ scaled_kwargs ["height" ] = int (scaled_kwargs ["height" ] * scale )
149
+ if scaled_kwargs .get ("width" ):
150
+ scaled_kwargs ["width" ] = int (scaled_kwargs ["width" ] * scale )
151
+ srcset .append (ImageCacheFile (generator_registry .get (generator_id , ** scaled_kwargs )))
134
152
135
153
attrs = {k : v .resolve (context ) for k , v in self ._html_attrs .items ()}
136
154
@@ -140,6 +158,9 @@ def render(self, context):
140
158
attrs .update (width = file .width , height = file .height )
141
159
142
160
attrs ['src' ] = file .url
161
+ if len (srcset ) > 0 :
162
+ attrs ['srcset' ] = f'{ file .url } 1x , ' + ' , ' .join (
163
+ f'{ entry [0 ].url } { entry [1 ]} x' for entry in zip (srcset , srcset_scales ))
143
164
attr_str = ' ' .join ('%s="%s"' % (escape (k ), escape (v )) for k , v in
144
165
attrs .items ())
145
166
return mark_safe ('<img %s />' % attr_str )
@@ -245,7 +266,11 @@ def thumbnail(parser, token):
245
266
246
267
The thumbnail tag supports the "--" and "as" bits for adding html
247
268
attributes and assigning to a variable, respectively. It also accepts the
248
- kwargs "format", "anchor", and "crop".
269
+ kwargs "format", "srcset", "anchor", and "crop".
270
+
271
+ To use "srcset" (generating multiple thumbnails for different pixel densities) list the scale factors::
272
+
273
+ {% thumbnail '100x100' mymodel.profile_image srcset='2 3' %}
249
274
250
275
To use "smart cropping" (the ``SmartResize`` processor)::
251
276
0 commit comments