1. Template engine

Documents: the aui. Making. IO/art – templat…

Making: github.com/aui/art-tem…

1.1. Problems in Ajax projects

  1. Data and HTML string concatenation leads to code confusion, error prone concatenation, increase the difficulty of modification.

  2. The business logic and user interface are mixed and the code is not easy to maintain.

for (var i = 0; i < result.length; i++) {
	html += '
      \ \ \ 
      \ '+ title +'\ \ \ +name+') "> hello, '+name+'Me this year'+age+'age \ 
      
    \
+hobbies[0] +'" >'+hobbies[0] +'\ \ \ '; } Copy the code

1.2. The role of the template engine

  1. Using the template syntax provided by the template engine makes the concatenation of data and HTML strings more beautiful and the code easier to maintain.
  2. The template engine can separate the data splicing of the user interface from the JavaScript business logic, increasing the scalability of the program.
  3. Using a template engine can improve development efficiency.
<h1>Hello, {{name}}, I am {{age}}</h1>
<ul>	
    {{each}}
    <li>{{$value.hobbies}}</li>
    {{/each}}
</ul>
Copy the code

1.3. Template rendering

<script src="./js/template-web.js"></script>
<script type="text/html" id="tpl">
 	<div>
		 <span>{{name}}</span>
		 <span>{{age}}</span>
    </div>
</script>
Copy the code
 // Concatenate a particular template with a particular data
 const html = template('tpl', {name: 'Joe'.age: 20
 }); 
Copy the code

2. Template syntax

The purpose of template syntax is to tell the template engine how to concatenate data and templates.

2.1. The output

Display the data in the template.

 <h2>{{value}}</h2>
 <h2>{{a ? b : c}}</h2>
 <h2>{{a + b}}</h2>
Copy the code

2.2. Output of original text

If the data contains HTML tags, by default the template engine will not parse the tags, but will escape them and output them in the original text.

<h2>{{@ value }}</h2>
Copy the code

2.3. Conditional judgment

{{if condition}}... {{/if}} {{if v1}} ... {{else if v2}} ... {{/if}}Copy the code
{{if}} < div > conditions show me < / div > {{else}} < div > condition was not show I < / div > {{/ if}}Copy the code

2.4. Cycle

 {{each target}}
     {{$index}} {{$value}}
 {{/each}}
Copy the code

2.5. Import template variables

<div>$imports.dataFormat(time)</div>
Copy the code
The template. The defaults. Imports. The variable name = variable values; $imports. Variable nameCopy the code
function dateFormat(Unformatted raw time){
    return 'Formatted current time'
}
template.defaults.imports.dateFormat = dateFormat;
Copy the code