Pre-populating HTML/Jade from Express/node.js web app

谁说我不能喝 提交于 2020-01-05 07:27:40

问题


I have a web app that is built using Express for node.js. I'm using Jade template files for the HTML displays. In one of these displays I'd like to have the various fields pre-populated with data. The data is being stored in a mongodb session store, as well as in a separate collection in the db. I'd prefer to use the session data to pre-populate these fields in the HTML/Jade displays. How can I go about doing this (if it's possible)?


回答1:


Add the defaults to res.locals and then set the input elements value attribute in jade.

//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)



回答2:


I figured it out by using res.render() from the Express API to do this. I will credit Plato with the answer though because his also seems to be correct and he's a nice man for answering my question.

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


来源:https://stackoverflow.com/questions/19386901/pre-populating-html-jade-from-express-node-js-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!