Handlebars动态对象括号选择器:基于动态值设置下拉框选中项的实现问题
Hey there, I’ve dealt with this exact dynamic property access issue in Handlebars before—let me break down how to fix it.
The core problem here is that Handlebars doesn’t support using a variable as a property name directly with its standard dot or bracket syntax (like .[some_attribute]). Instead, you need to use Handlebars’ built-in lookup helper to dynamically fetch the value from your selectedProduct object using the current attribute_code as the key.
Modified Code with lookup Helper
Here’s how to update your template to make this work:
<select name="{{attribute_code}}"> {{#each values}} <option value="{{value_index}}" {{#ifCond (lookup ../../selectedProduct ../../attribute_code) '==' value_index}} selected {{/ifCond}} > {{label}} </option> {{/each}} </select>
How This Works
- The
lookuphelper takes two arguments:- The object you want to access (
../../selectedProduct—we use the double../to traverse up two levels from the innervaluesloop to get the parent context’sselectedProduct). - The dynamic property name (
../../attribute_code—again, traversing up to get the current attribute’s code from the outer loop).
- The object you want to access (
When attribute_code is flavour, lookup will return the value of selectedProduct.flavour, which is then compared to value_index using your custom ifCond helper.
Bonus: Use Handlebars’ Built-in eq Helper (If Possible)
If you’re using Handlebars 4.0+, you can skip the custom ifCond helper and use the built-in eq helper for cleaner code:
<select name="{{attribute_code}}"> {{#each values}} <option value="{{value_index}}" {{#if (eq (lookup ../../selectedProduct ../../attribute_code) value_index)}} selected {{/if}} > {{label}} </option> {{/each}} </select>
This works because Handlebars supports subexpression syntax ((eq ...)) in newer versions, letting you chain helpers directly inside an if block.
The key takeaway is that lookup is Handlebars’ official way to handle dynamic property access—this should resolve your issue of mapping attribute_code to the correct property on selectedProduct dynamically.
内容的提问来源于stack exchange,提问作者Sandra Willford

