handlebars.js

Variables containing "." character in Handlebars?


I am using Handlebars templates. If I want to insert a variable in an hbs file, I add it as {{var_name}}.

The issue is, I have a large object with its keys taking formats similar to:

{
    "stats.name":"John",
    "stats.performance.day":123,
    "stats.performance.month":4567,
    "company":"My LLC"
}

If I try to add these to the Handlebars file as {{company}}, {{stats.name}}, {{stats.performance.day}}, {{stats.performance.month}} then only the {{company}} will be displayed. All other values come out blank, I assume because "." is a special character in Handlebars.

My question is, is there a way to override this, or do I actually need to iterate through this object and change every "." to a "_" or something before passing it to Handlebars to make it work?


Solution

  • I would recommend renaming your properties. Dot Notation is one of the two ways to access object properties in JavaScript. Typical code would look like: obj.prop. If your object's keys are not valid identifiers, then you must use Bracket Notation: obj['my-prop']. Since a dot is a property accessor, it is very unusual to see one in a property name. If I were to come across code written as obj['stats.performance.date'], I would assume it was a mistake and that obj.stats.performance.date was intended.

    With that said, Handlebars does support referencing properties that are not valid identifiers. This is called "segment-literal-notation", and it is as simple as wrapping square brackets around your identifier:

    {{[stats.performance.day]}}
    

    The documentation also states that:

    JavaScript-style strings, " and ', may also be used vs. [ pairs.

    So the following alternatives are valid:

    {{"stats.performance.day"}}
    {{'stats.performance.day'}}