2
\$\begingroup\$

I am using HandlebarsJS for my templating needs.

I have a nested object:

{
    "amount": {
        "preTax": 15.99,
        "tax": 0.0,
        "currencyCode": "USD",
        "total": 15.99
    }
}

And I have the following template:

{{#amount}}
<div>PreTax is {{preTax}}. Tax is {{tax}}. Currency Code is {{currencyCode}} and total is {{total}}</div>
{{/amount}}

Is this the best practice for accessing nested properties within a property? Like declaring the block for the data property or I need to use with?

Like so:

{{#with amount}}
<div>PreTax is {{preTax}}. Tax is {{tax}}. Currency Code is {{currencyCode}} and total is {{total}}</div>
{{/with}}

I know that both approaches work. And in mustache-js I always used the former approach.

\$\endgroup\$
1
\$\begingroup\$

Kevin Decker (one of the contributors Handlebars on Github) answered on the GitHub issue I had created.


The with form will be slightly faster than the generic block form due to some optimizations that can be made for known cases like that. You also have the option of making pathed lookups, {{amount.preTax}} for example. All work and unless you have extremely hot code I wouldn't worry too much about the performance of one vs. the other and leave to to which feels stylistically the best for you.

So I guess there is no real winner, unless as Kevin points out, you have an extremely used template then with might be a better option.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.