This article briefly describes the basic syntax of JsRender for object. Share it for your reference. The details are as follows:
As a JavaScript template engine, JsRender is essential to have a loop function, that is, for. However, because JsRender is too flexible, for can actually accept object as a loop object.
Both {{for Array}} and {{for Object}} are allowed. Everyone can understand {{for Array}}, which is to traverse an array and take out each element one by one. But {{for Object}} is a bit incredible, and the official documentation just gives an example that is not helpful, without any explanation.
At first, Xiaocai thought that the purpose of {{for Object}} was to traverse all the properties of the Object, but if you think about it carefully, this function {{props Object}} has been implemented. The function of the props tag is to traverse all the properties of the Object. The number of properties there are, the number of times will be looped. Each loop will have two hidden properties: key, prop, key represents the attribute name, and prop represents the attribute value, which is very convenient to use.
In fact, {{for Object}} is not a loop, it can be understood as entering (Into), that is, entering the Object environment and setting the current context to Object, similar to the with in Handlebars.js.
For example:
data:
Copy the code as follows: {
"title": "The A team",
"members": [
{
"name": "Pete",
"city": "members_city",
"address": {
"city": "address_city",
"city1": "address_city1",
"city2": "address_city2"
}
}
]
}
template markup:
Copy the code as follows: {{for members}}
{{for address}}
<p>.{{:city}}</p>
{{/for}}
{{/for}}
result:
The code copy is as follows: address_city
From the results, we can see that although members' item also has a city attribute, since they enter the Object pointed to by address through {{for address}}, {{:city}} is directly obtained from address.
At the same time, address has three properties, but only one line is output as a result, proving that {{for Object}} does not loop, just toggle this.
I hope this article will be helpful to everyone's JsRender programming learning.