模板引擎是第三方模块。让开发者以更加友好的方式拼接字符串,使项目代码更加清晰、更加易于维护。
模板引擎使用步骤:
1,在命令行工具中使用 npm install art-template 命令进行下载
2,使用const template = require(‘art-template‘)引入模板引擎
3,告诉模板引擎要拼接的数据和模板在哪 const html = template(‘模板路径’, 数据);
4,使用模板语法告诉模板引擎,模板与数据应该如何进行拼接
1 // 导入模板引擎 2 // 返回的template是一个方法 3 const template = require("art-template"); 4 5 // 导入路径拼接方法 6 const path = require("path"); 7 // 拼接路径 8 const views = path.join(__dirname,"views","index.art"); 9 10 // template 方法是用来拼接字符串的 11 // 参数1:模板的路径 绝对路径。绝对路径最后一个为文件名。文件名的后缀要为.art 12 // 参数2:对象,即要在模板中显示的数据 13 // 返回值:拼接好的字符串 14 const html = template(views,{ 15 name:"张三", 16 age:20 17 }); 18 19 console.log(html); 20 21 22 ------------------------------------------------------------ 23 // 使用模板引擎就要有模板,并且模板的后缀名为 .art 24 // 模板代码:在模板代码可以使用模板引擎中传过来的数据 25 26 <!doctype html> 27 <html lang="en"> 28 <head> 29 <meta charset="UTF-8"> 30 <title>Document</title> 31 </head> 32 <body> 33 34 {{name}} 35 36 {{age}} 37 38 39 </body> 40 </html>
art-template同时支持两种模板语法:标准语法和原始语法。
标准语法可以让模板更容易读写,原始语法具有强大的逻辑处理能力。
标准语法: {{ 数据 }} 原始语法:<%=数据 %>
------------
原文:https://www.cnblogs.com/yzy-kyk/p/12666082.html