2

Is there any way to access this within a conditional?

To explain a bit more… I have a loop over some items. I want to conditionally show the price if another value is set to something.

{
  "firstName": "Terry",
  "showPrice": "yes",
  "items": [
      { "itemName": "Item 1", "itemPrice": "23.99" },
      { "itemName": "Item 2", "itemPrice": "50.99" }
    ]
}
{{#each items }}

    <p>{{ this.itemName }}</p>
    
    {{#equals @root.showPrice "yes"}}

        <p>{{ this.itemPrice }}</p>
    
    {{/equals}}
    
{{/each}}

The issue seems to be due to going back to the @root to check against the showPrice value, it then breaks this being accessible.

I've tried things like:

{{ this.itemPrice }} // doesn't work
{{ @root.this.itemPrice }} // doesn't work
{{ @root.items.this.itemPrice }} // doesn't work
{{ @root.items.[0].itemPrice }} // can now access, but only the 0 index
{{ @root.items.@index.itemPrice }} // doesn't work

Does anyone have any ideas?

76484
  • 8,498
  • 3
  • 19
  • 30
Craig
  • 43
  • 6
  • 1
    Accessing the value from `@root` will not alter your `this` context. However, your helper might. Do you have the code for your `#equals` helper? – 76484 Oct 14 '20 at 14:58
  • 1
    Side note: I would advise that `showPrice` be a Boolean, not a String. – 76484 Oct 14 '20 at 15:00
  • 2
    This issue sometimes occurs when developers use an arrow-function to define their custom Handlebars helper without realizing that this affects the `this` context of the helper. See this answer: https://stackoverflow.com/a/49992169/3397771 – 76484 Oct 15 '20 at 15:46
  • As @76484 writes, this is entirely dependent on your custom `equals` helper. Taking a guess, it seems like there is a good chance maybe this custom helper uses an arrow-function, which binds `this` to its execution context. – romellem Oct 15 '20 at 17:24

0 Answers0