如何在 ember 模板中按 ID 查找对象

How to find an object by ID in an ember template

我有这样的数据结构:

let colors = {colorArray: [{id: 1, color: "blue"}, {id: 2, color: "red"}], anotherVariable: "anotherValue"}

我有一个这样的 each 帮手:

{{#each posts as |post|}}
    <div>...</div>
{{/each}}

我想要 return colors.colorArray 中与我正在迭代的 post 的 ID 相对应的对象。我不确定该怎么做。我尝试使用 ember-composable-helper,但没有任何记录(也没有错误)。这是我尝试过的:

{{#each posts as |post|}}
   {{#with (find-by 'id' post.id colors.colorArray) as |post|}}
      {{post}}
   {{/with}}
{{/each}}

我做错了什么?还有其他方法可以解决这个问题吗?

这里有几种方法可以解决这个问题:

  • 您可以将 post 和数组传递给组件。该组件应该有一个 属性 的计算 returns 颜色。然后在组件模板
  • 中使用计算出的 属性
  • 尝试使用 let helper 而不是 with,如果您的 Ember 版本有它。 With 很容易出事故。
  • 您可以将计算的 属性 直接添加到 posts 模型(如果您在应用中使用模型),returns 颜色正确。然后,您可以在应用程序的任何位置执行 post.color。当很多地方需要颜色的时候这样就好了。
  • 您可以编写一个(普通)助手,将 post 和颜色作为参数,returns 颜色

可组合的助手对于某些用例来说确实很方便,但这段代码非常适合在没有插件的情况下编写。