Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
MsDanglar opened this issue Jan 7, 2017 · 2 comments
Closed

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

MsDanglar opened this issue Jan 7, 2017 · 2 comments
Labels

Comments

@MsDanglar
Copy link

MsDanglar commented Jan 7, 2017

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
Copy link
Owner

BorisMoore commented Jan 7, 2017

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
Copy link
Author

Thank You

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants