星空网 > 软件开发 > 网页设计

Handlebars.js中集合(list)通过中括号的方式取值

有这么一个需求,在一个table中,tr是通过each取值,取出的值要与table标题相对应,如何实现?例如:

Handlebars.js中集合(list)通过中括号的方式取值Handlebars.js中集合(list)通过中括号的方式取值
<table> <thead>  <tr>    {{#each 标题集合,值举例[name,sex...]}}      {{this}}    {{/each}}    得到结果应是    <th>name</th>    <th>sex</th>  </tr> </thead> <tbody>  {{#each 内容集合,值举例[{name:'苏轼',sex:'男'},{name:'李清照',sex:'女'}...]}}   此时我想得到这样的数据,与标题想对应,该如何做呢?   <tr>     <td>苏轼</td>     <td>男</td>   </tr>   <tr>    <td>李清照</td>    <td>女</td>   </tr>  {{/each}} </tbody></table>

View Code

如果在JS中,我们可以通过list[key]的方式取值,但是handlebars好像不支持这种方式,不知道是不是我自己没整明白

总之资料了找了半天,也没有找到合适的解决方案,于是乎,自己写吧,很简单。

Handlebars.js中集合(list)通过中括号的方式取值Handlebars.js中集合(list)通过中括号的方式取值
Handlebars.registerHelper("getValueByKeyFromList", function(list, key, options){  if(list && key && list[key]){    return list[key];  }  return;});

View Code

应用到上面table中就是

Handlebars.js中集合(list)通过中括号的方式取值Handlebars.js中集合(list)通过中括号的方式取值
{{#each 内容集合,值举例[{name:'苏轼',sex:'男'},{name:'李清照',sex:'女'}...]}}  此时我想得到这样的数据,与标题想对应,该如何做呢?  <tr>   {{#each 标题集合,值举例[name,sex...]}}    <td>{{getValueByKeyFromList ../this this}}</td>    ../this 意为上一层集合的当前值    this 意为当前集合的当前值   {{/each}}  </tr>{{/each}}

View Code

解决。




原标题:Handlebars.js中集合(list)通过中括号的方式取值

关键词:JS

JS
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流