The example in this article describes the Jsrender for Index Loop index. Share to everyone for your reference. The specific analysis is as follows:
Jsredner and Jsviews (Jsviews is further encapsulated on a jsrender basis) known as the next generation of jquery templates, official address:
Https://github.com/BorisMoore/jsrender;
Https://github.com/BorisMoore/jsviews.
Loops are an essential part of the template engine, and talking about loops leads to a crucial factor: indexing.
The so-called index, that is, the number of cycles, through the index, can get the current loop is the first few times.
If the reader has read the official document, you will see the following way to get the index:
Data
Copy Code code as follows:
{
Names: ["Maradona", "Pele", "Ronaldo", "Messi"]
}
Template markup:
Copy Code code as follows:
{{for names}}}
<div>
<b>{{: #index +1}}.</b>
<span>{{: #data}}</span>
</div>
{{/for}}}
Result
Copy Code code as follows:
1. Maradona
2. Pele
3. Ronaldo
4. Messi
An index can be obtained in a loop by a special literal #index, the special literal #data equivalent to this, in this case each name is represented.
So let's do a little trick or something like that, but this time I want to show only the name that starts with M:
Data
Copy Code code as follows:
{
Names: ["Maradona", "Pele", "Ronaldo", "Messi"]
}
Template markup:
Copy Code code as follows:
{{for names}}}
{{if #data. IndexOf ("M") = = 0}}
<div>
<b>{{: #index +1}}.</b>
<span>{{: #data}}</span>
</div>
{{/if}}
{{/for}}}
Result
Copy Code code as follows:
Unavailable (nested view): Use #getIndex () 1. Maradona
Unavailable (nested view): Use #getIndex () 1. Messi
Simple add an If judge, unexpectedly error!
The problem is on the #index, the error message is clear, let you use #getindex () instead of #index.
Try the replaced code:
Data
Copy Code code as follows:
{
Names: ["Maradona", "Pele", "Ronaldo", "Messi"]
}
Template markup:
Copy Code code as follows:
{{for names}}}
{{if #data. IndexOf ("M") = = 0}}
<div>
<b>{{: #getIndex () +1}}.</b>
<span>{{: #data}}</span>
</div>
{{/if}}
{{/for}}}
Result
Copy Code code as follows:
What is this for? Simply put, it is because {{if}} does not create a regular data scope, but it interferes with the hidden scope. That is, {{if}} does not block the visibility of regular data (the data you pass in), but it interferes with the visibility of hidden data (#index, #parent). This is a simple understanding, and you don't have to delve into it, because this is just a flaw in the framework, not a standard.
Therefore, this article gives the reader a very important conclusion: try to use #getindex () to get index, avoid using #index, unless your application is simple enough.
I hope this article will help you to learn jsrender.