Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Last active December 7, 2016 17:29
Show Gist options
  • Save willbroderick/1ecb0ac6f7f511f7de0e to your computer and use it in GitHub Desktop.
Save willbroderick/1ecb0ac6f7f511f7de0e to your computer and use it in GitHub Desktop.
Fill an HTML template with an arbitrary Shopify product, with AJAX
/*
Fill an HTML template with a Shopify product
MIT license.
Example use:
<span class="prev" data-fill-with-product="{{ collection.previous_product | split: '/' | last }}">
<script type="text/template">
<a href="{{ collection.previous_product }}" title="[encode:title]">
<span class="title">[title]</span>
<img src="[img:600x]" />
</a>
</script>
</span>
$('[data-fill-with-product]').fillWithShopifyProduct();
*/
$.fn.fillWithShopifyProduct = function(){
return $(this).each(function(){
//Which product are we getting & where are we putting it?
var handle = $(this).data('fill-with-product');
var $replaceTarget = $(this).find('script[type="text/template"]');
var template = $replaceTarget.html();
//Fetch data
$.getJSON('/products/' + handle + '.json', function(data){
var product = data.product;
//Encoded for attributes
var $tempEl = $('<div>');
for(var key in product) {
var encoded = $tempEl.html(product[key]).text().replace(/"/g, '&quot;').replace(/'/g, '&rsquo;');
template = template.replace(new RegExp('\\[encode:' + key + '\\]', 'ig'), encoded);
}
//Simple values
for(var key in product) {
template = template.replace(new RegExp('\\[' + key + '\\]', 'ig'), product[key]);
}
//Image src, e.g. "[img:250x]"
var lastDot = product.image.src.lastIndexOf('.');
template = template.replace(/\[img:([0-9a-z]*)\]/ig, product.image.src.slice(0, lastDot) + '_$1' + product.image.src.slice(lastDot));
//Output
$replaceTarget.replaceWith(template);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment