是否有可能从MongoDB获取数据并在服务器端为一个node-js项目呈现一个html模板?
截至目前,在我的服务器端js文件中,我已完成以下操作。
//Failing array will be populated by a db.find later on.
var failing = [
{
name: "Pop"
},
{
name: "BOB"
}];
/*Now i have to send a mail from the server for which I'm using nodemailer.
Where do i store the template ? This is what I've done in the same file */
var template = "<body>{#failing} <p>{.name}</p> {/failing}</body>"
// Add this as the body of the mail and send it.
我不确定如何渲染数据以及如何显示数据。我知道将模板存储在变量中是不对的,但我不确定还能做什么。
答案 0 :(得分:0)
如果模板那么短,则可以毫无问题地将其存储在变量中。显然,您也可以将其存储在文件中。
假设您决定将其存储在文件index.dust
中:
<body>{#failing} <p>{.name}</p> {/failing}</body>
现在,在您的节点控制器中,您需要加载文件并从中生成html内容:
const fs = require('fs');
const dust = require('dustjs-linkedin');
// Read the template
var src = fs.readFileSync('<rest_of_path>/index.dust', 'utf8');
// Compile and load it. Note that we give it the index name.
var compiled = dust.compile(src, 'index');
dust.loadSource(compiled);
// Render the template with the context. Take into account that this is
// an async function
dust.render('index', { failing: failing }, function(err, html) {
// In html you have the generated html.
console.log(html);
});
选中documentation,以免每次使用时都必须编译模板。