Answered

Handlebars {{#with}} helper doesn't work for array elements, does it?

This is half bug report and half question asking if there is another way to achieve the same thing.

In my XML template we have a lot of direct array element access by index, for example:

<Id>{{this.0.id}}</Id>
<sku>{{this.0.Name}}</sku>
<description>{{this.0.Description}}</description>

Handlebars has the {{#with}} helper states (from the docs):

The with-helper allows you to change the evaluation context of template-part.

However, if you try to use {{#with}}... with - array elements you'll receive errors. Consider this example:

{{#with this.0}}
<Id>{{id}}</Id>
<sku>{{Name}}</sku>
<description>{{Description}}</description>
{{/with}}

Would be sweet, but instead:

Message: Parse error on line 9:
... {{#with this.0}}
-----------------------^
Expecting 'ID', got 'NUMBER'

 

Has anyone found a syntax tweak to allow using the {{#with}} helper to set context to an array element?

0

Comments

4 comments
Date Votes
  • Official comment

    Hi Courtney,

    Nice to hear from you and thanks for the reply. I can confirm that your example compiles and works. It doesn't quite achieve what I was after so I tried to nest two {{#with}} statements to get into the context of the array element like so:

    {{#with this}}
    {{#with 0}}
    {{id}}
    {{/with}}
    {{/with}}

    No bueno - that doesn't work either. No error, but {{id}} evaluates to '' (empty string). I tried bracket notation and that DOES work:

    {{#with this}}
    {{#with [0]}}
    {{id}}
    {{/with}}
    {{/with}}

    So that's better than nothing. I'd still love it if handlebars could use

    {{#with this[0]}}

    Update: On a whim, I tried:

    {{#with this.[0]}}

    And it works! Eureka!

    Celigo should document this or have an example using it as I think it makes for much cleaner and more maintainable template code.

     

     

     

  • Hi Steve Klett,

    Thanks for letting us know about this need and what you encountered. I'm checking with our experts on this and will get back to you as soon as possible.

    0
  • Hi Steve Klett,

    In the "with" statement, you don't set the index on the array object at first. Essentially, #with saves you from typing out the array object name for each element in the array you want to return. Using your example from above, please change it to the following:
    {{#with this}}
    <Id>{{0.id}}</Id>
    <sku>{{0.Name}}</sku>
    <description>{{0.Description}}</description>
    {{/with}}

    Let us know if that doesn't work!

    0
  • Hi Steve Klett

    Thank you so much for letting us know of this solution you found! We will definitely get this documented as soon as we can. We really appreciate you sharing this!

    0

Please sign in to leave a comment.

 

Didn't find what you were looking for?

New post