模板引擎art template
一兵拢、模板引擎基礎(chǔ)概念
1.模板引擎:第三方模塊
2.art-template模板引擎
在命令行工具中使用npm install art-template 命令進(jìn)行下載;
使用const template = require ('art-template')引入模板引擎;
高速模板引擎要拼接的數(shù)據(jù)和模板在哪 const html = tempalte('模板路徑',數(shù)據(jù));
使用模板語法告訴模板引擎逾礁,模板與數(shù)據(jù)應(yīng)該如何進(jìn)行拼接说铃。
3.代碼示例
//導(dǎo)入模板引擎模塊
const template = require('art-template');
//將特定模板與特定數(shù)據(jù)進(jìn)行拼接
const html = template('./views/index.art',{
? ? ? data : {
? ? ? ? name : '張三',
? ? ? ? age : 20
? ? ? }
});
<div>
? ? <span>{{data.name}}</span>
</div>
二、模板引擎語法
1.模板語法
art-template同時(shí)支持兩種模板語法:標(biāo)準(zhǔn)語法和原始語法嘹履。
標(biāo)準(zhǔn)語法可以讓模板更容易讀寫腻扇,原始語法具有強(qiáng)大的邏輯處理能力。
標(biāo)準(zhǔn)語法{{數(shù)據(jù)}
原始語法<%=數(shù)據(jù)%>
2.輸出
將某項(xiàng)數(shù)據(jù)輸出在模板中植捎,標(biāo)準(zhǔn)語法和原始語法如下:
<h2>{{value}}</h2>
<h2><%= value %></h2>
3.原文輸出
如果數(shù)據(jù)中攜帶HTML標(biāo)簽衙解,默認(rèn)模板引擎不會(huì)解析標(biāo)簽,會(huì)將其轉(zhuǎn)義后輸出焰枢。
標(biāo)準(zhǔn)語法{{@數(shù)據(jù)}
原始語法<%-數(shù)據(jù)%>
<h2>{{@value}}</h2>
<h2><%- value %></h2>
4.條件判斷
標(biāo)準(zhǔn)語法
{{if 條件}}? ...? {{/if}}
{{if vl}}...{{else if v2}}...{{/if}}
原始語法
<% if (value) { %> ... <%} else if (v2) { %> ... <%} %>
5.循環(huán)
標(biāo)準(zhǔn)語法{{each 數(shù)據(jù)}}
原始語法<% for(){%><%}%>
{{each target}}
? ? ? {{$index}} {{$value}}
{{/each}}
<% for(var i=0; i<target.length;i++){%>< = i %}%> <%= target[i]%>
<%}%>
6.子模板
使用子模板可以將網(wǎng)站公共區(qū)塊(頭部蚓峦、底部)抽離到單獨(dú)的文件中舌剂。
標(biāo)準(zhǔn)語法{{include '模板'}}
原始語法<%include('模板')%>
{{include './header.art'}}
<% include ('./header.art') %>
7.模板繼承
8.模板繼承示例
<!doctype html>
? <html>
? ? ? <head>
? ? ? ? ? <meat charset="utf-8">
? ? ? ? ? <title>HTML</title>
? ? ? </head>
? ? ? <body>
? ? ? ? ? {{block 'content'}}{{/block}}
? ? ? </body>
? ? </html>
{{extend './layout.ary'}}
{{block 'head'}}? <link rel="stylesheet" href="custom.css"> {{/block}}
{{block 'content'}} <p>This is just an awesome page.</p>{{/block}}
9.模板配置
向模板中導(dǎo)入變量template.defaults.imports.變量名=變量值;
設(shè)置模板根目錄template.defaults.root=模板目錄
設(shè)置模板默認(rèn)后template.default.extname='.art'ingmoding
三、第三方模塊router
功能:實(shí)現(xiàn)路由
使用步驟:獲取路由對(duì)象暑椰、調(diào)用旅游對(duì)象提供的方法創(chuàng)建路由霍转、啟用路由,使路由生效
const getRouter = require('router')
const router = getRouter();
router.get=('/add',(req,res) => {
? ? ? res.end('Hello World')
})
server.on('request',(req,res) => {
? ? router(req,res)
})