第一次使用节点和模板引擎(是的,我知道,糟糕的地方,“开始”,但无论如何)。我正在从一个json流构建一些内容,最后我想将这些内容吐出到我的html页面中的div中,如下所示(更新的)高速公路片段:
app.get('/foo', function (req, res) {
//... get my stream called 'mystream'
//... get ready to append content for items found in json stream
var htmlbuf = "";
//now process the json stream:
oboe(mystream)
.node('{bar}', function(aBar){
//eventually, I'd like to actually append individual new DOM elements,
//but for now I'll settle for just spitting out raw html:
var buffer = '<p>Found a bar with name'+ aBar.name + '</p>';
res.render('index', {itemsfound: htmlbuf});
});
});index.pug:
doctype html
html
head
link(type='text/css', rel='stylesheet', href='./css/main.css')
title Hello
body
h1 Hello world!
div#results.listing
items= itemsfound我得到错误‘错误:不能设置标题后,他们被发送’。所以我认为问题是oboe.node()在任何时候都在发射,而我没有在正确的时间发送响应内容?连接oboe.node()事件所需的代码/框架是什么,以便它们能够在我的pug模板中目标或创建dom元素并正确地发送响应?谢谢。
发布于 2016-08-26 14:37:33
你需要这样做:
app.get('/foo', function (req, res, next) {
//... get my stream called 'mystream'
//... get ready to append content for items found in json stream
var htmlbuf = "";
//now process the json stream:
oboe(mystream)
.node('{bar}', function(aBar){
//eventually, I'd like to actually append individual new DOM elements,
//but for now I'll settle for just spitting out raw html:
htmlbuf += '<p>Found a bar with name' + aBar.name + '</p>';
})
.on('fail', function (err) {
res.statusCode = err.statusCode
next(err.thrown)
})
.on('done', function () {
res.render('index', {itemsfound: htmlbuf});
});
});发布于 2016-08-25 23:29:04
好吧,我试试。
如果您希望呈现带有计算内容的页面,那么
// js
app.get('/foo', function (req, res) {
res.locals.var1 = 'Res.locals.var1'; // you can define vars here too
if (!req.xhr)
// send as html-page
res.render('page.jade', {bar: smth-content, title: 'Hello world'}); // without var1
else
// send as json on ajax-request
res.json({bar: smth-content, title: 'Hello world'});
});
// .jade
doctype html
html
head
link(type='text/css', rel='stylesheet', href='./css/main.css')
|
title #{title}
body
h1 Hello world!
|
#{bar} #{var1}要混合模板代码,您可以使用extends和include玉石关键字。或者这个技巧(不推荐)
// js
app.get('/foo', function (req, res) {
res.render('row.jade', {myblock: smth-content}, function(err, html) {
if (err)
return res.send(err.message);
res.render('page.jade', {myblock: html});
});
});
// page.jade
doctype html
html
head
link(type='text/css', rel='stylesheet', href='./css/main.css')
body
#{myblock}
// myblock.jade
p Found a bar with name #{myblock}https://stackoverflow.com/questions/39150564
复制相似问题