Auto-generate srcset and sizes attributes for an image in Django. This script
makes a few assumptions about your site structure and uses them to create
srcset
and sizes
attributes for an <img>
tag.
- At a browser width of
DESIGN_WIDTH
, the image width will match the value passed to srcset - At a browser widths between
MOBILE_MAX
andMAX_WIDTH
, the image will resize proportionally - At browser widths above
MAX_WIDTH
, the image size will be proportional toMAX_WIDTH
- At a browser widths below
MOBILE_MAX
, all images render at 100% width
Either easy_thumbnails or sorl-thumbnail is required.
The following can be configured in your django settings (default values shown)
SRCSET_REFERENCE_WIDTH = 1440
SRCSET_DESKTOP_MAX = 2000
SRCSET_MOBILE_MAX = 767
SRCSET_MOBILE_MIN = 375
In a jinja2 template, if sorl.thumbnail.get_thumbnail
and srcset.srcset
are
exposed as global variables, and obj.image
is a django
ImageField
then the following template code:
{% set thumb = get_thumbnail(obj.image, '1020x816', crop='center') %}
<img src="{{ thumb.url }}" {{ srcset(image, '1020x816', crop='center') }}>
will result in something like
<img src="/media/../1020x816.jpg"
srcset="/media/../image-1020x816.jpg 1020w,
/media/../image-2040x1632.jpg 2040w,
/media/../image-750x600.jpg 750w"
sizes="(max-width: 767px) 100%,
(min-width: 768px and max-width: 2000px) 70.83%,
(min-width: 2001px) 1417px">
please explain more, where should I put this code. Usage part is unclear