You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Handlebars动态对象括号选择器:基于动态值设置下拉框选中项的实现问题

Solution for Dynamically Setting Selected Option in Handlebars Dropdown

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 lookup helper takes two arguments:
    1. The object you want to access (../../selectedProduct—we use the double ../ to traverse up two levels from the inner values loop to get the parent context’s selectedProduct).
    2. The dynamic property name (../../attribute_code—again, traversing up to get the current attribute’s code from the outer loop).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 04:47:32