【问题标题】:Pass variables to template将变量传递给模板
【发布时间】:2017-11-10 23:07:21
【问题描述】:

我使用 NodeJS/Expressjs,我有这条路线:

router.post({

   var value = req.body.value;
   //I NEED TO DO SOMETHING LIKE
   var file = '../test/test.js';
   file.render(value);

});

和 /test/test.js 看起来像

var myVar = {value1};
var someStruct = {key: {value2}}
function Test(){
  var info = {value3};
}

这样做的好方法是什么? 我可以使用一些模板系统吗?

问候,

【问题讨论】:

    标签: javascript node.js express templating


    【解决方案1】:

    查看 EJS 模板系统。满足你的要求。

    // server.js
    // load the things we need
    var express = require('express');
    var app = express();
    
    // set the view engine to ejs
    app.set('view engine', 'ejs');
    
    // pass and object/string into the render function as the second arg.
    app.post('/your-url', function(req, res) {
        let data = {
            object: 'string'
        };
        res.render('pages/index', data);
    });
    
    app.listen(8080);
    console.log('8080 is the magic port');
    

    【讨论】:

    • 是的,我正在使用 ejs,但我想将呈现的代码保存到 javascript 磁盘文件中。
    猜你喜欢
    • 2019-04-03
    • 2011-05-08
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多