JsRender for index circular index usage

  • 2020-03-30 04:12:16
  • OfStack

The example of this article describes the JsRender for index loop index. Share with you for your reference. Specific analysis is as follows:

JsRedner and JsViews (JsViews is further packaging on the basis of JsRender) are 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 a template engine, and speaking of loops leads to one crucial factor: indexing.

The so-called index, that is, the number of cycles, through the index, you can get the current cycle is the number of times.

If you read the official document, you will see the following way to obtain the index:

Data:

{
   names: ["Maradona","Pele","Ronaldo","Messi"]
}

The template markup:

{{for names}}
   <div>
     <b>{{: #index+1}}.</b>
     <span>{{: #data}}</span>
   </div>
 {{/for}}

The result:

1. Maradona
 2. Pele
 3. Ronaldo
 4. Messi

The index can be obtained in a loop by the special literal #index, the special literal #data is equivalent to this, and in this case represents each name.

Data:

{
   names: ["Maradona","Pele","Ronaldo","Messi"]
 }

The template markup:

{{for names}}
   {{if #data.indexOf("M") == 0}}
     <div>
       <b>{{: #index+1}}.</b>
       <span>{{: #data}}</span>
     </div>
   {{/if}}
 {{/for}}

The result:

 Unavailable (nested view): use #getIndex()1. Maradona
 Unavailable (nested view): use #getIndex()1. Messi

Simply add an if to judge, unexpectedly report wrong!

The problem is #index, and the error is very clear, let you use #getIndex() instead of #index.

Try the replacement code:

Data:

 {
   names: ["Maradona","Pele","Ronaldo","Messi"]
 }

The template markup:

 {{for names}}
   {{if #data.indexOf("M") == 0}}
     <div>
       <b>{{: #getIndex()+1}}.</b>
       <span>{{: #data}}</span>
     </div>
   {{/if}}
 {{/for}}

The result:

 1. Maradona
 4. Messi

Why is that? Simply put, this is because {{if}}, while not creating a regular data scope, 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 easy to understand without going into it, because this is just a flaw in the framework, not a standard.

Therefore, this article gives the reader an important conclusion: use #getIndex() to get the index and avoid #index unless your application is simple enough.


Related articles: