Handlebars is a JS library, so why does it need a dot before array index values such as
data.array.[0]
instead of
data.array[0]

- 173
- 1
- 10
-
It must be a preprocessor of JS, because that's not valid JS syntax. – Barmar Aug 25 '16 at 16:34
-
i may have been wrong to call it a library instead of a preprocessor, but i still don't understand the design choice to use this 'dot bracket' notation – Sdarb Aug 25 '16 at 16:35
2 Answers
The square brackets are "segment-literal notation":
To reference a property that is not a valid identifier, you can use segment-literal notation:
{{#each articles.[10].[#comments]}} <h1>{{subject}}</h1> <div> {{body}} </div> {{/each}}
As you can see, you use square brackets to "quote" identifier that might be problematic as bare identifiers in an expression path, like #comments
. This category of problematic identifiers also includes identifiers that are integers (as array indices are) when they come at the end of an path; see this answer on How do I access an access array item by index in handlebars?
As for why they simply didn't do away with the dot entirely when using square-bracket syntax for problematic identifiers (e.g., foo[#comments]
), I can't say for sure, but it does seem nicely consistent for readability to ensure that the segments of a path are always separated by periods.
-
this is exactly the answer i was looking for. Thanks a lot for the write up and explanation. – Sdarb Aug 25 '16 at 17:35
Handlebars.js
is an enhanced version of Mustache
library. I would guess it uses similar grammar for parsing as Mustache
so this dot-notation must somehow come from there.

- 4,052
- 3
- 29
- 34