Could someone elaborate on this example from the Musicon project (handlebars.js)

Hey guys, just working my way through the Musicon project as part of the JS path, and came across this step which for some reason completely baffles me. Could someone please elaborate on the example provided as to what’s happening and why? I can’t seem to figure out why there are two price elements before the sale and one after.

<script id="templateHB" type="text/x-handlebars-template">
  {{#each instruments}}
  <article class="instrument">
    <img class="image" src="{{image}}" alt="{{name}}">
    <section class="details">  
      <h2 class="name">{{this.name}}</h2>
      <p class="description">{{this.description}}</p>
      {{#if sale}}
      <p class="price"><del>Price: {{this.price}}</del></p>
      <p class="sale">On Sale! {{this.sale}}</p>
      {{else}}
      <p class="price">Price: {{this.price}}</p>
      {{/if}}
    </section>
  </article>
  {{/each}}
</script>

Well this has to do with the condition if there is a sale or not.

if there is a sale then there is an adjusted price:

<p class="price"><del>Price: {{this.price}}</del></p>
      <p class="sale">On Sale! {{this.sale}}</p>

If there is no sale the else kicks in with the regular price:

<p class="price">Price: {{this.price}}</p>

Does this answer your question?

Kind of, what I still don’t understand is why the normal price and sale price directly under the first if statement and why the else is afterwards? why isn’t it for example:

{{if}}
Normal price
{{else}}
Sale price ?

Well in programming the else commonly used as the default which makes sense in this case since the normal price is probably used most of the time.

But it doesnt really matter and you may reverse them but then you would have to change the condition for the if…else statement. something like:

{{#if !sale}}
      <p class="price">Price: {{this.price}}</p>
      
      {{else}}
      <p class="price"><del>Price: {{this.price}}</del></p>
      <p class="sale">On Sale! {{this.sale}}</p>
      
      {{/if}}
1 Like

Thanks Jannes, your example just highlighted why I was getting so confused - in the second statement the first price is deleted so it compares with the sale price, if there is indeed a sale on.

Thanks again! :smiley:

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.