BorisMoore / jsviews

Interactive data-driven views, MVVM and MVP, built on top of JsRender templates
http://www.jsviews.com/#jsviews
MIT License
855 stars 130 forks source link

Get next loop value in {^{for}} #357

Closed MsDanglar closed 7 years ago

MsDanglar commented 7 years ago

Hi Boris, Im have next basic code

{^{for object}}
<tr><td>{{:Name}}</td></tr>
{{/for}}}

but im wont in current loop get a next loop name value as next code

for(var i=0; i<obj.length;i++)
{
obj[i+1].Name   **(here im get a next loop  name value in current loop)**
}

How can im to do it in jsview ? thankyou

BorisMoore commented 7 years ago

There are a few different ways you can do that. But remember that on the last iteration of the loop, the next object is undefined. So you need a null check, before getting the Name value.

Here is one way - using a contextual template parameter, ~arr to get at the array from within the loop item block.

{^{for objects ~arr=objects}}
  <tr>
    <td>This name: {{:Name}}</td>
    <td>{{:~arr[#index+1].Name onerror=''}}</td>
  </tr>
{{/for}}}

See: https://www.jsviews.com/#contextualparams http://www.jsviews.com/#onerror

By using onerror='' you avoid having to do a null check such as an {{if ~arr[#index+1]}}...{{/if}} wrapper.

And here is another approach. Create a custom tag:

$.views.tags("get", function(index, field) {
    var obj = this.tagCtx.view.get("array").data[index];
    return obj ? obj[field] : "";
});

and then use it like this {{get #index+1 'Name'/}}, to get the Name of the next object. Here the null check is in code.

Yet another approach would be to create a custom helper function such as ~get(index, field) and write {{:~get(#index, 'Name')}}.

A better place for this kind of question is probably on Stack Overflow. Could you perhaps post your question there, so I can then post this reply, so other people can find it more easily than here in clsoed issues, and be helped with similar scenarios? Thanks.

MsDanglar commented 7 years ago

Thank You