To use the artTemplate template engine, you need to import this JS file. Type is fixed to type=”text/ HTML “, so that the page will not display this line of code, template code can be placed anywhere on the page, call it from append or HTML variables in the template engine to fill in {{}}, write all the variables that need to fill in the object, if you just need to loop, can be an array
- Example 1: This example writes variables to data, passing
template('temp', data)
The template generates the HTML code for the page and writes it to a div with the ID of Container using innerHtml.{{each city value i}}{{/each}}
Represents for arraysdata.city
The circulation,data.city.length
Is 6, so loop six times, writing the variable value each time.
<body>
<div id="container"></div>
<script id="temp" type="text/html">
<h1>{{title}}</h1>
<ul>
{{each city value i}}
<li>{{value}}</li>
{{/each}}
</ul>
</script>
<script>
var data = {
title: 'city',
city: ['jiangsu'.'Shanghai'.'Beijing'.'chengdu'.'shenzhen'.'hangzhou']}; document.getElementById('container').innerHTML = template('temp', data);
</script>
</body>
Copy the code
- Example 2: When the template contains only loop statements, the data type is array, we need to use
$data
Represents the array, where if{{each city value i}}{{/each}}
Without value and I, you can use values from arraysvalue:$value
.index:$index
<body>
<div id="container"></div>
<script id="temp" type="text/html">
<ul>
{{each $data value i}}
<li>{{value}}</li>
{{/each}}
</ul>
</script>
<script>
var city = ['jiangsu'.'Shanghai'.'Beijing'.'chengdu'.'shenzhen'.'hangzhou'];
document.getElementById('container').innerHTML = template('temp', city);
</script>
</body>
Copy the code
- In addition, the template engine can use conditional statements
{{if value}} ... {{/if}}
And filters{{a ? b : c}}
The default value{{a || b}}
And expression operation{{a + b}}