jeudi 3 décembre 2015

How to access an array position in a ember template?

I'm experiencing some frustration trying to do a simple thing in Ember.
I know that all the mess comes from spliting up logic from templates, but I think what I'm trying to achieve is not so expensive.
I have a model which returns me a list of items, those items have a related property and depending if the value of that property is repeated, the template should show something or not.
My returned data should look like this:

[{id :0,
  text:"Element 0",
  nested_property: {
    value:'Value 1'
  }
},{id :1,
  text:"Element 1",
  nested_property: {
    value:'Value 1'
  }
},{id :2,
  text:"Element 2",
  nested_property: {
    value:'Value 2'
  }
},{id :3,
  text:"Element 3",
  nested_property: {
    value:'Value 2'
  }
},{id :4,
  text:"Element 4",
  nested_property: {
    value:'Value 1'
  }
}]

what I want to produce is something like this:

<ul>
  <li>
    <span>Value 1</span>
    <span>Element 0</span>
  </li>
  <li>
    <span>Element 1</span>
  </li>
  <li>
    <span>Value 2</span>
    <span>Element 2</span>
  </li>
  <li>
    <span>Element 3</span>
  </li>
  <li>
    <span>Value 1</span>
    <span>Element 4</span>
  </li>
</ul>

My first thought was: "Well, I keep the value of the actual loop on a variable, and compare in the next loop. If it's different override the value."
As we cannot use "if" to compare two variables, I had to create a component to do that. So that part of the problem is solved.
What I'm facing now is how to keep track of the last loop value, cause my component needs it to compare with the actual value.
I cannot access to a certain element inside the loop using any of those options:

{{#each model as |element key|}}
    {{model.0.text}}
    {{model[0].text}}
    {{model[key-1].text}} <--- That would be awesome if works :D
{{/each}}

Any thoughts? maybe another way to approach the problem?




Aucun commentaire:

Enregistrer un commentaire