在使用Ember.js的HBS模板中设置变量。

huangapple go评论136阅读模式
英文:

set variable in hbs template using ember.js

问题

我有一个数据数组,我需要在我的hbs模板中对其进行迭代:

{{#each-in myArray.[0] as |key value|}}
  <th>
    {{value}}
  </th>
{{/each-in}}

{{#each-in myArray.[1] as |key value|}}
  <th>
    {{value}}
  </th>
{{/each-in}}

如何声明一个变量并增加它以替换硬编码的值?

我尝试使用{{#let}}包装,但没有成功:

{{#let index=0}}
  {{#each-in myArray.[index] as |key value|}}
    <th>
      {{value}}
    </th>
  {{/each-in}}
{{/let}}

我正在使用ember 2.13。

英文:

I have an array of data and I need to iterate over it in my hbs template:

{{#each-in myArray.[0] as |key value|}}
  &lt;th&gt;
    {{value}}
  &lt;/th&gt;
{{/each-in}}

{{#each-in myArray.[1] as |key value|}}
  &lt;th&gt;
    {{value}}
  &lt;/th&gt;
{{/each-in}}

How do I declare a variable and increase it to replace the hardcoded value?

I tried to wrap with {{#let}} but that did not worked:

{{#let index=0}}
  {{#each-in myArray.[index] as |key value|}}
    &lt;th&gt;
      {{value}}
    &lt;/th&gt;
  {{/each-in}}
{{/let}}

I'm using ember 2.13.

答案1

得分: 1

你已经非常接近了!

{{#let 0 as |index|}}
  {{#each-in (get myArray index) as |key value|}}
    <th>
      {{value}}
    </th>
  {{/each-in}}
{{/let}}

关于 let 的文档:https://api.emberjs.com/ember/5.0/classes/Ember.Templates.helpers/methods/let?anchor=let

关键要点是模板使用了不同的语法,可以在这里找到描述:https://cheatsheet.glimmer.nullvoxpopuli.com/docs/templates

这是一个可工作的演示

(请注意,这使用了新的 gjs 格式,教程在这里:https://tutorial.glimdown.com)

英文:

You're very close!

{{#let 0 as |index|}}
  {{#each-in (get myArray index) as |key value|}}
    &lt;th&gt;
      {{value}}
    &lt;/th&gt;
  {{/each-in}}
{{/let}}

The docs on let: https://api.emberjs.com/ember/5.0/classes/Ember.Templates.helpers/methods/let?anchor=let

The key-take-aways is that the templates use a different syntax, which is described here, https://cheatsheet.glimmer.nullvoxpopuli.com/docs/templates

Here is a working demo

(Note this uses the new gjs format, tutorial here: https://tutorial.glimdown.com)

答案2

得分: 0

这最终对我有用了,多亏了NullVoxPopuli的答案,让我找对了方向。由于某些原因,{{#let}} 没有起作用。

在这里发布以防有人需要:

<tr>
{{#each-in myArray as |index object|}}
<tr>
{{#each-in (get myArray index) as |key value|}}
<th>
{{value}}
</th>
{{/each-in}}
</tr>
{{/each-in}}
</tr>

英文:

This has finally worked for me, thanks to NullVoxPopuli's answer that put me on the right way. For some reasons, {{#let}} was not working.

Posting it in the case anybody could need it:

&lt;tr&gt;
  {{#each-in myArray as |index object|}}
  &lt;tr&gt;
    {{#each-in (get myArray index) as |key value|}}
    &lt;th&gt;
      {{value}}
    &lt;/th&gt;
    {{/each-in}}
  &lt;/tr&gt;
  {{/each-in}}
&lt;/tr&gt;

huangapple
  • 本文由 发表于 2023年7月4日 21:04:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76612952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定