Search code examples
javascripthandlebars.js

Handlebars - Pass variable into a dot notation


I'm trying to reuse a partial called rater-table.hbs which looks like this

 <div class="comparison-rater-container">
  {{> rater-table header="Key Stakeholder" valueType=KeyStakeholder}}
  {{> rater-table header="Group 1" valueType=Group1}}
  {{> rater-table header="Group 2" valueType=Group2}}
  {{> rater-table header="Other Stakeholders" valueType=OtherStakeholders}}
</div>

In my other file I'm able to call the header variable just fine but I'm having trouble getting the valueType to fit the bracket notation. I'm trying to use it like this

{{ ../pole.summary.benefits.[(valueType)] }}

If I hard code the word Group1, it works fine but otherwise it gives me a null value. Any way to get this working in handlebars?


Solution

  • The way to lookup a dynamic property on an Object in Handlebars is by using the lookup helper. This would look like:

    {{lookup ../pole.summary.benefits valueType }}
    

    However, the lookup needs a string value which will be the property to lookup on the Object that is the first argument. For this reason, you will want to be sure to wrap quotes around each value you are assigning to valueType. Without the quotes, Handlebars is going to try to evaluate each of these as properties of the current context Object and they will all end up passing valueType=undefined to the partial.

    The template must become:

    <div class="comparison-rater-container">
        {{> rater-table header="Key Stakeholder" valueType="KeyStakeholder"}}
        {{> rater-table header="Group 1" valueType="Group1"}}
        {{> rater-table header="Group 2" valueType="Group2"}}
        {{> rater-table header="Other Stakeholders" valueType="OtherStakeholders"}}
    </div>
    

    Alternatively, you could forgo the lookup and just pass each value directly to the partial:

    {{> rater-table header="Key Stakeholder" value=../pole.summary.benefits.KeyStakeholder }}
    

    I have created a fiddle for reference.