Handlebars Renderer iDisplay Product
uses generic template or bespoke
by Ben Clayton
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.js"></script>
<div class="product-list">
<div class="group-wrapper modelid-{{id}} product-list-item">
<img src="{{picture}}'" class="picture" /><h3>
{{name}}</h3>
<br/> {{currency}}{{price}}
<br/>
</div>
<div class="group-wrapper modelid-100 product-list-item">
<img src="{{picture}}" class="picture" />This is a Multipack of 10 cans of {{name}}<br/> <br/> Total for all cans {{currency}}{{price}}<br/>
</div>
</div>
CSS
.product-list-item {
border: 1px solid red;
width: 300px;
padding: 5px;
margin: 4px;
background-color: #FFFFD0;
opacity: 1;
overflow: hidden;
}
.product-list-item img {
float: right;
}
JavaScript
var products = [{
"id": 99,
"name": "Lime Cordial",
"price": 1.23,
"currency": "£",
"picture": "https://cdn.shopify.com/s/files/1/0667/2089/products/smg330u_compact.jpg?v=1528209848"
}, {
"id": 100,
"name": "Coke",
"price": 13.21,
"currency": "£",
"picture": "https://www.sainsburys.co.uk/wcsstore7.36.10/ExtendedSitesCatalogAssetStore/images/catalog/productImages/22/5449000059222/5449000059222_L.jpeg"
}, {
"id": 101,
"name": "Lemon",
"price": 1.32,
"currency": "£",
"picture": "https://cdn.shopify.com/s/files/1/0667/2089/products/smg330u_compact.jpg?v=1528209848"
}, {
"id": 102,
"name": "Orange",
"price": 1.27,
"currency": "£",
"picture": "https://cdn.shopify.com/s/files/1/0667/2089/products/smg330u_compact.jpg?v=1528209848"
}];
var tmpls = {};
function render() {
// Pickup the templates and store keyed by the id (0 if no id found)
$(".product-list-item").each(function() {
console.log("generic", $(this).hasClass("modelid-{{id}}"))
var cls = $(this).attr('class');
var matches = cls.match(/modelid-(\d+)/);
var id = matches ? matches[1] : 0;
console.log("id:", id);
tmpls[id] = this.outerHTML;
});
// empty the area where the products will be placed
$(".product-list").empty();
// render all the products, using either the generic template, or the unique template
// which has the matching id.
products.forEach(function(product) {
console.log(product);
var tmpl = tmpls[product.id] || tmpls[0];
var compiledTmpl = Handlebars.compile(tmpl);
$('.product-list').append(compiledTmpl(product));
})
}
render();