forked from adamculpepper/eleventy-plugin-responsive-images
-
Notifications
You must be signed in to change notification settings - Fork 0
/
.eleventy.js
37 lines (34 loc) · 1.55 KB
/
.eleventy.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
module.exports = function(eleventyConfig, pluginNamespace) {
eleventyConfig.namespace(pluginNamespace, () => {
eleventyConfig.addShortcode('respimg', parameter => {
var errors = '';
if (!parameter.src) {
errors += 'src parameter missing!';
} else if (!parameter.sizes) {
errors += 'sizes parameter missing!';
}
if (errors) {
return '<span style="background:lightsalmon; color:#fff; padding:5px;">' + errors + '</span>';
} else {
const hostname = eleventyConfig.hostname ? eleventyConfig.hostname : '';
const arraySizes = parameter.sizes.replace(/ /g,'').split(',');
const maxSize = Math.max.apply(Math, arraySizes);
const baseUrl = `https://res.cloudinary.com/${eleventyConfig.cloudinaryCloudName}/image/fetch/`;
const imageSrc = `${baseUrl}q_auto,f_auto,a_ignore,w_${maxSize}/${hostname}${parameter.src}`;
const srcset = arraySizes.map(width => {
return `${baseUrl}q_auto,f_auto,a_ignore,w_${width}/${hostname}${parameter.src} ${width}w`;
}).join(',');
return '<img ' +
(parameter.width ? ' width="' + parameter.width + '"' : '') +
(parameter.height ? ' height="' + parameter.height + '"' : '') +
(parameter.sizes ? ' sizes="(max-width: ' + maxSize + 'px) 100vw, ' + maxSize + 'px"' : '') +
' src="' + imageSrc + '"' +
' srcset="' + srcset + '"' +
(parameter.alt ? ' alt="' + parameter.alt.trim() + '"' : '') +
(parameter.class ? ' class="' + parameter.class + '"' : '') +
(parameter.loading ? ' loading="' + parameter.loading + '"' : '') +
'>';
}
});
});
};