当前位置:网站首页>Template engine, making interaction elegant
Template engine, making interaction elegant
2022-06-22 09:19:00 【Jdoit CW】
The goal is
Understand the template engine
Can use template syntax
Write it at the front
Write it at the front : When we get the data of the server response , How do we render it , Of course, I think you are smart enough to specify a template engine . alas ( I don't want to suffer from Template Strings anymore ), Template engines have a wide range of uses , It can be used for back-end rendering (npm install ), You can also perform front-end rendering ( This article takes the front-end rendering as an example ). Of course, no matter which rendering method , The template syntax is consistent .
1. template engine
This article focuses on the common syntax of template engine , More grammar tips , Please give priority to official documents
file :http://aui.github.io/art-template/zh-cn/
Github: https://github.com/aui/art-template
1.1 Disadvantages of Using Template Strings
- Data and HTML String concatenation leads to code confusion , Splicing is error prone , Increase modification difficulty .
- Business logic and user interface are mixed , The code is not easy to maintain .
for (var i = 0; i < result.length; i++) {
html += '<!DOCTYPE html>\ <html lang="en">\ <head>\ <meta charset="UTF-8">\ <title>'+ title +'</title>\ </head>\ <body>\ <h1 οnclick="sayHi('+name+')"> Hello ,'+name+' I this year '+age+' year </h1>\ <ul>\ <li title="'+hobbies[0]+'">'+hobbies[0]+'</li>\ </ul>\ </body>\ </html>';
}
1.2 The role of template engine
- Using the template syntax provided by the template engine, you can Make data and HTML String splicing is more beautiful , Code is easy to maintain .
- The template engine enables the data splicing and editing of the user interface JavaScript Business logic separation , Increase program scalability .
- Using the template engine, you can Improve development efficiency .
1.3 Use of template engine
Template rendering is a four step process :
- Download and import template-web.js file
- Write a template where you want to render
- Use template Method for data splicing
- Render the spliced template string at the specified position
Code demonstration ( The notes are clear )
<!-- The introduction of the file -->
<script src="./template-web.js"></script>
<div id="box">
<!-- Use... Where you need to render script Tag write html Templates ( Be careful 1:type="text/html",2:id Required ),type For in script Write in html convenient ,id Easy to determine render target -->
<script type="text/html" id="tpl"> <div> <!-- Rendered values must be in "{
{}}" The parcel --> <span>{
{
name}}</span> <span>{
{
age}}</span> </div> </script>
</div>
<script> // When introducing template-web After the document ,template Methods exist // Note that one parameter of the method is the template id, The second parameter is the data to be rendered // Method returns the concatenated template string const html = template('tpl', {
name: ' Chen Wen ', age: 18 }); // Render the spliced data to the specified location document.querySelector('#box').innerHTML = html </script>
2. Template syntax
The function of template syntax is to tell the template engine , How to splice data and templates .
2.1 Output
Display the data in the template .
<h2>{
{value}}</h2>
<h2>{
{a ? b : c}}</h2>
<h2>{
{a + b}}</h2>
2.2 Original output
If the data carries HTML label , By default , The template engine will not parse the tag , It will be escaped and output to the original text . If we need to HTML Label effective , You need to add... Before the data @, Parse label .
<h4>{
{@ value }}</h4>
2.3 conditional
If there is a certain judgment in the rendering of some data ( Render or not ), We can limit it by conditional judgment
{
{if Conditions }} ... {
{/if}}
{
{if v1}} ... {
{else if v2}} ... {
{/if}}
Show or not
{
{if Conditions }}
<div> Conditions established Show me </div>
{
{else}}
<div> Conditions not established Show me </div>
{
{/if}}
Be careful :if Double label
2.4 loop
For the data that the server responds , Most of them are arrays 、json object . There are many such data , In this case, the template syntax loop is used
{
{each target}}
{
{$index}} {
{$value}}
{
{/each}}
Be careful :each Double label , among $index Is the index of the current circular item ,$value Is the value of the current loop item
demo preview :

Code demonstration ( The notes are clear )
<script src="template-web.js"></script>
<script type="text/html" id="tpl">
<ul>
{
{
each data}}
<li>
<!-- Be careful $values It's the object , Use ”." To take a value -->
<span> full name :{
{
$value.name}}</span>
<span> Age :{
{
$value.age}}</span>
</li>
{
{
/each}}
</ul>
</script>
<script>
let data = [{
name: ' Jiaxi ',
age: 27
}, {
name: ' Zhan Jie ',
age: 27
}, {
name: ' Xiaofei ',
age: 27
}]
const html = template('tpl', {
// data: data
data //es6 The key value data is consistent , Omittable value ,( Note that this must be an object format , Add {})
});
document.body.innerHTML = html
</script>
2.5 Import template variables
When the template processes some native data , May be used JavaScript Methods , But this method template engine does not , At this point, you need to import this method into the template engine ( Import the variables )
<div>$imports.dataFormat(time)</div>
template.defaults.imports. Variable name = A variable's value ;
$imports. Variable name
demo preview :
Original time format

Demand time format 
The first way :
<script src="./template-web.js"></script>
<script type="text/html" id="tpl">
<h1>{
{
$imports.dateFormat(time)}}</h1>
</script>
<script>
const html = template('tpl', {
time: new Date()
})
document.body.innerHTML = html
// Define functions that change the format of dates
function dateFormat(time) {
return time.getFullYear() + ' year ' + (time.getMonth() + 1) + ' month ' + time.getDate() + ' Japan '
}
</script>
Be careful : This method , The function is defined in the global scope , So the template can be used directly $.imports call
The second way :
<script src="./template-web.js"></script>
<script type="text/html" id="tpl">
<!-- Methods after exposure , Here you can call , You can also omit $imports -->
<h1>{
{
$imports.dateFormat(time)}}</h1>
</script>
<script>
window.addEventListener('load', function() {
// Leak out the method , Note that this statement must be written before splicing template data
template.defaults.imports.dateFormat = dateFormat;
const html = template('tpl', {
time: new Date()
})
document.body.innerHTML = html
// Define functions that change the format of dates
function dateFormat(time) {
return time.getFullYear() + ' year ' + (time.getMonth() + 1) + ' month ' + time.getDate() + ' Japan '
}
})
</script>
Be careful : In most cases , Prevent variable pollution , They are generally defined as local methods , use template.defaults.imports. Custom name = Method name Expose the method
At the end
At the end : Template engine has been widely used in the current page rendering , Master its usage , essential . Of course, more usage , We have to rely on the government to greatly : file , I hope we can continue to make breakthroughs , On the way , come on. .
边栏推荐
- Shell中的单中括号和双中括号的区别
- threejs实现简单全景看房demo
- 循环队列超详细实现,小白秒懂
- 文件小能手---multer
- 函数总结(1)
- XSS vulnerability attack
- Originality: dozens of lines of pure PHP code decrypt goto encrypted PHP single file [for learning only]
- Record some Oracle operation commands
- MySQL中常用的SQL语句
- Php+mysqli create a table, read multiple items, add, modify and query a complete instance
猜你喜欢

User insight into the video industry in January 2022: active users began to pick up under the influence of holidays

When easypoi imports the secondary header data of an excel file, the data in the first column of the @excelentity entity class is null
![Local visualization method of xshell remote server tensorboard/visdom [one-step test is effective]](/img/42/6f5121c472e25990df98c2b119b8c9.png)
Local visualization method of xshell remote server tensorboard/visdom [one-step test is effective]

MSSQL injection of SQL injection

Machine learning | nltk_ Data download error |nltk's stopwords corpus download error solution

前馈和反向传播
![In the monorepo learning, execute NPM run build to report error[err\u require\esm] of ES module](/img/76/ec4776bcd452584290ef8bf5d0e06f.jpg)
In the monorepo learning, execute NPM run build to report error[err\u require\esm] of ES module

Didi's two-sided summary

DOM programming
![Wireless routing attack and WiFi password cracking practice [penetration technology]](/img/b9/3551630c128e03731a956c6a6502e2.jpg)
Wireless routing attack and WiFi password cracking practice [penetration technology]
随机推荐
There are three ways to traverse the map. Second, you know
Unicode characters / static non static access
锁-ReentrantLock
General ASP reads CSV files and displays all rows and columns as tables
项目优化+上线(掌握了么?)
Continuous training on tensorflow breakpoint (principle + code explanation)
WebRTC系列-网络传输之IceConfig及stunPing失败处理
求余弦的大小
嵌入式开发专业术语概念汇总
5 interview questions, grasp the underlying principle of string!
循环队列超详细实现,小白秒懂
OpenCV每日函数 直方图相关(3)
文件小能手---multer
Pytorch oserror: DLL load failed: problem solving
IS_ ERR()
Two threads execute i++ 100 times respectively, and the possible values obtained
Cocoscreator compilation error record could not write cache value gradle\daemon\4.10.3\regi
Development error reporting record
list_head
Shell中的单中括号和双中括号的区别