我希望以下控制器返回一个 html 字符串作为响应。目前正在控制器中对字符串进行硬编码,我觉得这不是正确的方法。
router.get('/', function(req, res) {
var employeeDetails; // JSON File Containing Details
// I need ejs to build the page using employeeDetails and store that as a
// string and return this string as the response
});
如果将模板作为字符串,则可以调用ejs.render(template)
。
您必须先将模板文件作为字符串读取,因此最终会执行以下操作:
import * as ejs from 'ejs';
import { readFile as _readFile } from 'fs';
import { promisify } from 'util';
const readFile = promisify(_readFile);
router.get('/', async function(req, res) {
const template = await readFile(/* your template */, 'utf-8');
const employeeDetails = await readFile(/* your json file */, 'utf-8');
const html = ejs.render(template, { /* your data */ });
// now you have your rendered html as a string
// and can e.g.:
res.send(html);
});
据我了解您的问题,遵循解决方案。您可以渲染页面并将 JSON 作为对象发送,并在前端使用 EJS 渲染它们...
router.get('/', function(req, res) {
var employeeDetails; // JSON File Containing Details
employeeDetails=employeeDetails.parse;
res.render('your site',{data:employeeDetails});
});
试试这个?