26-Node.js学习笔记-art-template模板引擎使用

1.1 模板引擎

模板引擎是第三方模块

让开发者以更加友好的方式拼接字符串,使项目代码更加清晰,更加易于维护。

1.2 art-template模板引擎

1.命令行工具中使用 npm install art-template 命令进行下载
2.使用const template = require('art-template') 引入模板引擎
3.告诉模板引擎要拼接的数据和模板在哪 const html = template('模板路径',数据);

1.3 art-template 代码示例

//导入模板引起模块
const template = require(' art-template');
//将特定模板与特定数据进行拼接
const html = template('./views/index.art',{
    data:{
        name:'柠檬不酸',
        age:18
    }
})


//
<div>
    <span>{{data.name}}</span>
    <span>{{data.age}}</span>
</div>

demo

//导入模板引擎
const template  = require('art-template');
const path = require('path');
//template方法是用来拼接字符串的
//1.模板路径 绝对路径
const views = path.join(__dirname,'views','index.art')

//2.要在模板中显示的数据,对象类型
//返回拼接好的 字符串
const html = template(views,{
    name:'柠檬不酸',
    age:18

})
console.log(html)
//template/views/index.art
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  {{name}}
  {{20}}
</body>
</html>

2.1 模板语法

art-template同时支持两种模板语法:标准语法原始语法

标准语法可以让模板更容易读写,原始语法具有强大的额逻辑处理能力

标准语法:{{数据}}
原始语法:<%=数据%>

2.2输出

将某项数据输出在模板中,标准语法与原始语法如下:

//标准语法:{{数据}}
{{value}}
{{a+b}}
//原始语法:<%=数据%>
<%=value%>
<%=a+b%>

2.3原文输出

如果数据中携带html标签,默认模板引擎不会解析标签,会将其转义后输出

//标准语法:{{数据}}
{{@数据}}

//原始语法:<%=数据%>
<%-数据%>

demo2


const template  = require('art-template');
const path = require('path');

const views = path.join(__dirname,'views','01.art')
const html = template(views,{
    name:'柠檬不酸',
    age:18,
    content:'<h2>我是标题</h2>'

})
console.log(html)
//template/views/01.art
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  //标准语法
  <p>{{name}}<p>
  <p>{{age}}<p>
  <p>{{1+1==2?'相等':'不相等'}}<p>
  <p>{{content}}<p>
  <p>{{@content}}<p>
  //原始语法
  <p><%=name%></p>
  <p><%=age%></p>
  <p><%=1+1==2?'相等':'不相等'%></p>
  <p><%=content%><p>
  <p><%-content%><p>
</body>
</html>

2.4条件判断

在模板中可以根据条件来决定显示哪块html代码

猜你喜欢

转载自www.cnblogs.com/foreverLuckyStar/p/12094691.html
今日推荐