简体   繁体   中英

Why does handlebars use dot bracket notation for accessing arrays by index?

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]

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 (eg, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM