This article describes the JsRender for index loop index. Share it for your reference. The specific analysis is as follows:
JsRedner and JsViews (JsViews is a further encapsulation based on JsRender) are called the next generation of Jquery templates, the official address:
https://github.com/BorisMoore/jsrender;
https://github.com/BorisMoore/jsviews.
Loops are an essential part of the template engine, and when it comes to loops, a crucial factor is introduced: indexing.
The so-called index is the number of loops. Through the index, you can get the current loop how many times it is.
If readers have read the official document, they will see the following ways to obtain the index:
data:
Copy the code as follows: {
names: ["Maradona","Pele","Ronaldo","Messi"]
}
template markup:
Copy the code as follows:{{for names}}
<div>
<b>{{: #index+1}}.</b>
<span>{{: #data}}</span>
</div>
{{/for}}
result:
Copy the code as follows: 1. Maradona
2. Pele
3. Ronaldo
4. Messi
The index can be obtained in the loop by a special literal #index, which is equivalent to this, and in this case represents each name.
Next, let’s make some tricks, and the example above, but this time I hope to only display names starting with M:
data:
Copy the code as follows: {
names: ["Maradona","Pele","Ronaldo","Messi"]
}
template markup:
Copy the code as follows:{{for names}}
{{if #data.indexOf("M") == 0}}
<div>
<b>{{: #index+1}}.</b>
<span>{{: #data}}</span>
</div>
{{/if}}
{{/for}}
result:
Copy the code as follows: Unavailable (nested view): use #getIndex()1. Maradona
Unavailable (nested view): use #getIndex()1. Messi
I simply added an if judgment and it actually reported an error!
The problem lies in #index. The error message is very clear. You can use #getIndex() instead of #index.
Try the replaced code:
data:
Copy the code as follows: {
names: ["Maradona","Pele","Ronaldo","Messi"]
}
template markup:
Copy the code as follows: {{for names}}
{{if #data.indexOf("M") == 0}}
<div>
<b>{{: #getIndex()+1}}.</b>
<span>{{: #data}}</span>
</div>
{{/if}}
{{/for}}
result:
Copy the code as follows: 1. Maradona
4. Messi
Why is this? Simply put, it is because although {{if }} does not create a regular data scope, it interferes with the hidden scope. That is, {{if }} will not block the visibility of regular data (the data you pass in), but will interfere with the visibility of hidden data (#index, #parent). This is a simple understanding, and there is no need to go into it, because this is just a flaw of this framework, not a standard.
Therefore, this article gives readers an important conclusion: try to use #getIndex() to get the index and avoid using #index unless your application is simple enough.
I hope this article will be helpful to everyone's JsRender's learning.