Skip to content

Instantly share code, notes, and snippets.

@stewartknapman
Last active May 22, 2017 00:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stewartknapman/a4cb0d34d0c68f7b5eaa4e833790326f to your computer and use it in GitHub Desktop.
Save stewartknapman/a4cb0d34d0c68f7b5eaa4e833790326f to your computer and use it in GitHub Desktop.
Take a some Shopify content, such as product.description or page.content and add `srcset` to any of its images.
{% capture func %}
{% comment %}
Scan String:
Scan a string looking for things
Parameters:
Content: the content to be scaned
Split: the item to split the string with
Start: the thing that says we can start collecting
Stop: the thing that says we can stop collecting
{% endcomment %}
{% assign parts = content | split: split | join:'~~' | replace: '>', '>~~' | replace: '<', '~~<' | split: '~~' %}
{% assign capturing = false %}
{% capture captured %}{% endcapture %}
{% for a in parts %}
{% unless a == blank %}
{% if a == start %}
{% assign capturing = true %}
{% endif %}
{% if capturing %}
{% capture captured %}{{ captured }} {{ a }}{% endcapture %}
{% endif %}
{% if capturing and a contains stop %}
{% assign capturing = false %}
{% endif %}
{% endunless %}
{% endfor %}
{% assign _scan_string_result = captured | replace: '>', '>~~' | replace: '<', '~~<' | split: '~~' %}
{% endcapture %}
{% capture func %}
{% comment %}
SRCSET:
Take a some content, such as product.description or page.content and add `srcset` to any of its images.
Parameters:
Content: the content to be searched
Widths: a comma separated list of UNITLESS widths to be used in the srcset attribute
Sizes: a string to be used as the sizes attribute value
{% endcomment %}
{% assign new_content = content %}
{% assign ws = widths | split:',' %}
{% include '_scan_string' content: content, split: ' ', start: '<img', stop: '>' %}
{% assign imgs = _scan_string_result %}
{% for i in imgs %}
{% unless i == blank %}
{% assign attrs = i | split: ' ' %}
{% for a in attrs %}
{% if a contains 'src=' %}
{% assign src = a %}
{% assign file = a | split: '/' | last | split: '?' | first %}
{% endif %}
{% endfor %}
{% if file %}
{% capture srcset %}{% endcapture %}
{% for w in ws %}
{% assign x = w | append: 'x' %}
{% capture srcset %}{{ srcset }}{{ file | file_img_url: x, format: 'pjpg' }} {{ w }}w{% unless forloop.last %}, {% endunless %}{% endcapture %}
{% endfor %}
{% capture new_src %}src="{{ file | file_img_url: '64x', format: 'pjpg' }}" srcset="{{ srcset }}" sizes="{{ sizes }}"{% endcapture %}
{% assign new_content = new_content | replace: src, new_src %}
{% endif %}
{% endunless %}
{% endfor %}
{% endcapture %}{{ new_content }}
{% include '_srcset' content: product.description, widths: '320,640,768,900,1024,1200,1440,2048', sizes: '100vw' %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment