【问题标题】:Pre-populating HTML/Jade from Express/node.js web app从 Express/node.js Web 应用程序预填充 HTML/Jade
【发布时间】:2013-10-23 14:13:23
【问题描述】:

我有一个使用 Express for node.js 构建的 Web 应用程序。我正在为 HTML 显示使用 Jade 模板文件。在其中一个显示中,我希望在各个字段中预先填充数据。数据存储在 mongodb 会话存储中,以及 db 中的单独集合中。我更喜欢使用会话数据在 HTML/Jade 显示中预填充这些字段。我该怎么做(如果可能的话)?

【问题讨论】:

    标签: html node.js mongodb express pug


    【解决方案1】:

    将默认值添加到res.locals,然后在jade 中设置input 元素value 属性。

    //node.js
    app.get('/', function(req, res){
      // Sorry I am unfamiliar with Mongo, not sure the syntax...
      mongo.get('defaults', function(err, body){
        res.locals.dName = body.defaultName;
        res.locals.dFoo = body.defaultFoo;
        res.render('myTemplate');
      });
    });
    
    //myTemplate.jade
    !!!
    html
      body
        form(action='/form', method='post')
          input#formName(name='name', value=locals.dName)
          input#formFoo(name='foo', value=locals.dFoo)
    

    【讨论】:

    • 如果可以直接传递给res.render(),为什么还要使用res.locals
    • 个人喜好,主要是...另外,有时我会从后面的中间件调用res.render,使用res.locals 是一种保存值的便捷方法,而无需将它们传递给后面的中间件以其他方式发挥作用
    • 我同意 res.locals 在中间件链中传递数据非常有用,只是从未见过有人在与调用 res.render 的位置相同的位置使用它 :)
    • local 变量是某种计算的结果而不是仅仅分配现有事物的情况下,它也更具可读性。例如res.render('myTemplate', {dName:someFunction('foo', 'bar'), dFoo:someOtherFunction(JSON.stringify(baz, null,2))})
    【解决方案2】:

    我通过使用 Express API 中的 res.render() 来解决这个问题。不过,我会将答案归功于柏拉图,因为他的答案似乎也是正确的,而且他是回答我问题的好人。

    exports.viewProfile = function(req, res) {
        res.render('viewProfile', {username: req.session.user, firstname: req.session.firstname});
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-20
      • 2018-12-25
      • 2013-04-17
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 2011-08-24
      • 1970-01-01
      • 2010-12-04
      相关资源
      最近更新 更多