I am try to add various IF() operators to check if an image exsists and if one price is greater than another, but not sure the correct syntax when working with template literals.
Here is a a function that loops over each product and outputs the title, image and price, just not sure how to use ternary operators here.
if(products.length > 0) {
products.forEach(function(product, index) {
const productRow = `
<div class="col-md-3 col-lg-3 col-sm-6 col-xs-6 init">
<div class="product-item mb-0 wow fadeIn" data-wow-offset="10" data-wow-duration="1s" data-wow-delay="500ms">
<div class="product-thumb">
<div class="reveal img-fluid">
<a href="${product.url}"><img class="img-fluid" src="${product.images[0]}" /></a>
</div>
</div>
<div class="product-content py-2">
<h3><a href="${product.url}">${product.title}</a></h3>
<p class="home-price-inline mb-0">
<span class="js-price" data-default-price="{{ current_variant.price | money }}">${Currency.formatMoney(product.price_min)}</span>
<s class="ml-0">${Currency.formatMoney(product.compare_at_price)}</s>
</p>
</div>
</div>
</div>`;
productRecomendationBody.insertAdjacentHTML('afterbegin', productRow);//afterbegin is the first element directly after the parent element
});
}
If you want to render an image only when it's available then you can do something like this.
Refer this section
<a href="${product.url}">${product.images[0] ? '<img class="img-fluid" src='${product.images[0]}' />' : ""}</a>
if (products.length > 0) {
products.forEach(function(product, index) {
const productRow = `
<div class="col-md-3 col-lg-3 col-sm-6 col-xs-6 init">
<div class="product-item mb-0 wow fadeIn" data-wow-offset="10" data-wow-duration="1s" data-wow-delay="500ms">
<div class="product-thumb">
<div class="reveal img-fluid">
<a href="${product.url}">${product.images[0] ? '<img class="img-fluid" src='${product.images[0]}' />' : ""}</a>
</div>
</div>
<div class="product-content py-2">
<h3><a href="${product.url}">${product.title}</a></h3>
<p class="home-price-inline mb-0">
<span class="js-price" data-default-price="{{ current_variant.price | money }}">${Currency.formatMoney(product.price_min)}</span>
<s class="ml-0">${Currency.formatMoney(product.compare_at_price)}</s>
</p>
</div>
</div>
</div>`;
productRecomendationBody.insertAdjacentHTML('afterbegin', productRow); //afterbegin is the first element directly after the parent element
});
}
I am try to add various
if()operators...
just not sure how to use ternary operators.
With an if you split the string.
var i = 2;
var row = `${i} second`;
if (i!==1)
row+='s';
row += " to go";
console.log(row)
with a ternary you can also split the string and keep it inline (here, spread over multiple lines for clarity, but could be one line)
var i = 2;
const row = `${i} second`
+ (i!==1?"s":"")
+ ` to go`;
console.log(row)
or you can put the ternary in a replacement, using ${}
var i = 2;
const row = `${i} second${i!==1?"s":""} to go`;
console.log(row)