Last active
December 19, 2022 16:14
-
-
Save BroFox86/364039252e6e617273ee8360fd65d349 to your computer and use it in GitHub Desktop.
[Responsive image] Pug/Nunjucks responsive image mixin/macro #responsive
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{% macro respImg( | |
class, | |
srcset, | |
sizes, | |
src, | |
width = "", | |
height = "", | |
loading = "", | |
alt = "" | |
)%} | |
<img | |
class="{{ class }}" | |
srcset="{{ srcset }}" | |
sizes="{{ sizes }}" | |
src="{{ src }}" | |
{% if width %} width="{{ width }}" {% endif %} | |
{% if height %} height="{{ height }}" {% endif %} | |
{% if loading %} loading="{{ loading }}" {% endif %} | |
alt="{{ alt }}" | |
/> | |
{% endmacro %} | |
{# {{ respImg( | |
class = "__img", | |
srcset = "images/image.png 300w, images/[email protected] 600w", | |
sizes = "(min-width: 1000px) 400px, (min-width: 768px) 300px, 100vw", | |
src = "images/image.png", | |
loading = "lazy", | |
alt = "" | |
)}} #} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mixin respImg(src, initialWidth) | |
- const src1 = `${src} ${initialWidth}w` | |
- const src2 = `${src.replace(/(\.[\w]+)/, "@1\.5x$1")} ${Math.round(initialWidth * 1.5)}w` | |
- const src3 = `${src.replace(/(\.[\w]+)/, "@2x$1")} ${Math.round(initialWidth * 2)}w` | |
img(srcset = `${src1}, ${src2}, ${src3}`, src = src)&attributes(attributes) | |
//- Input | |
+respImg("images/flower.jpg", 300)(class="block__img" sizes="(min-width: 1000px) 400px, (min-width: 768px) 300px, 100vw" alt="Rose") | |
//- Output | |
<img class="block__img" srcset="images/flower.jpg 300w, images/[email protected] 450w, images/[email protected] 600w" sizes="(min-width: 1000px) 400px, (min-width: 768px) 300px, 100vw" src="images/flower.jpg" alt="Rose"/> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment