Skip to content

Instantly share code, notes, and snippets.

@BroFox86
Last active December 19, 2022 16:14
Show Gist options
  • Save BroFox86/364039252e6e617273ee8360fd65d349 to your computer and use it in GitHub Desktop.
Save BroFox86/364039252e6e617273ee8360fd65d349 to your computer and use it in GitHub Desktop.
[Responsive image] Pug/Nunjucks responsive image mixin/macro #responsive
{% 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/image@2x.png 600w",
sizes = "(min-width: 1000px) 400px, (min-width: 768px) 300px, 100vw",
src = "images/image.png",
loading = "lazy",
alt = ""
)}} #}
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/flower@1.5x.jpg 450w, images/flower@2x.jpg 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