问题
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