handlebars.jsbigcommercecornerstone

Display Element Based on Two Custom Fields Values in BigCommerce Cornerstone Stencil Theme


I have a div I want to display on the product detail page when a given product has two custom fields that contain a particular value. For example, every product in my catalog has the following custom fields

I want to conditionally display a div element when a product's InventoryOnOrder > 0 AND it's InventoryInStore = 0. Any help on how I can get something along the lines of the following snippet to work would be greatly appreciated!

{{#each custom_fields}}
    {{#if (toLowerCase name) '===' 'inventoryonorder'}}
        {{#if value '!=' 0}}
            {{#if (toLowerCase name) '===' 'inventoryinstore'}}
                {{#if value '===' 0}}
                    <div>element A</div>
                {{/if}}
            {{/if}}
        {{/if}}
    {{/if}}
{{/each}}

Thank you in advance for being smarter than I :) Cheers!


Solution

  • The best way to go about this wouldn't be to handle the logic and render the component in the #each loop. Instead, you should use the #each loop to iterate the keys of the custom_fields and check if the current iteration has the inventoryonorder or inventoryinstore name, and if it does, then you should use the assignVar helper to set the variable for each one and handle the logic later outside of the #each block.

    I was able to write a working example in my Stencil environment, here's my code:

    {{#each product.custom_fields}}
        {{#if (toLowerCase name) "===" "inventoryonorder"}}
            {{assignVar "field_inventoryOnOrder" value}}
        {{/if}}
        {{#if (toLowerCase name) "===" "inventoryinstore"}}
            {{assignVar "field_inventoryInStore" value}}
        {{/if}}
    {{/each}}
    
    {{#all (if (getVar "field_inventoryOnOrder") ">" "0") (if (getVar "field_inventoryInStore") "===" "0")}}
        <div>Display custom message</div>
    {{/all}}
    

    Notice that in the each loop, I don't render any content - this loop is pure handlebars and it's used to set the variables for comparison later. The assignVar helper is very useful if you haven't heard of it yet!

    Immediately after the each loop handles the logic to assign the handlebars variable, I use the #all helper to make sure all of the parameters resolve true. If they do, then the content should be rendered.