服务端ssr渲染,原理是模版引擎+渲染数据,处理完成后返回给客户端。
node中有个第三方库ejs,可以处理模版引擎的渲染。
模版引擎:
<!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> <%arr.forEach(a => {%> <li><%=a%></li> <%})%> </body> </html>
ejs渲染:
let ejs = require('ejs'); let fs = require('fs'); let path = require('path'); let data = {arr: [1,2,3]}; // 编码格式必须有 let templateStr = fs.readFileSync(path.resolve(__dirname, './index.html'), 'utf-8'); let str = ejs.render(templateStr,data); console.log(str);
模拟ejs.render方法:
let ejs = require('ejs'); let fs = require('fs'); let path = require('path'); let data = {arr: [1,2,3]}; // 编码格式必须有 let templateStr = fs.readFileSync(path.resolve(__dirname, './index.html'), 'utf-8'); // let str = ejs.render(templateStr,data); // 模拟实现ejs的render方法 function render(str, data) { str = str.replace(/<%=([\s\S]*?)%>/g, function() { return '${' + arguments[1] + '}'; }) // 拼接成一个使用with传递数据的模版字符串 let head = 'let str;\r\n with(obj){str=`'; // 使用非贪婪匹配 let content = str.replace(/<%([\s\S]*?)%>/g, (match, group) => { // 拼接字符串时注意;的添加 return '`;' + group + ';str+=`'; }); let tail = '`}; return str;'; console.log(head + content + tail); // obj为形参 let fn = new Function('obj', head + content + tail); return fn(data); } let str = render(templateStr, data); console.log(str);
来源:https://www.cnblogs.com/lyraLee/p/12208140.html