如何通过JSON输出Jade内容? (Node.js的)

时间:2012-02-24 01:28:09

标签: json node.js express pug

几个月前我在CodeIgniter中写了一个视频库网络应用程序,我试图将后端移动到Node,使用Express + Jade来生成内容。 PHP版本将JSON发送到前端,通常包括大量的HTML。

我想用Jade渲染HTML位(因为它就是它的用途),但显然我想以JSON格式输出它,而不是直接输出到浏览器。如何做到这一点可能很痛苦,但我现在无法理解......任何帮助都非常感激。

原始PHP

ob_start();

for ($i = $start; $i < $end; $i++)
{
    $v = $videos[$i];
    echo '<a id="video-' . $v->url . (isset($v->otherid) ? '-' . $v->otherid : '') . '" href="#!' . Settings::$pretty_link . '/' . $v->url . (isset($v->otherid) ? '/' . $v->otherid : '') . '" class="Box' . ($i == $start ? " Batch" : "") . '" title="Click to view the ' . $v->name . '"><img src="' . site_url('images/thumb/' . $v->image) . '" alt="The ' . $v->name . '" /><span>' . $v->name . '</span></a>';
}

$data[$html] = ob_get_clean();

// Add some other things to $data

echo json_encode($data);

闪亮的新玉

- var v
- for (var i = view.start; i < view.end; i++) {
-   v = view.videos[i]
    a(id="#{v.url + (v.otherid === null ? "" : "-" + v.otherid)}", 
        href="#!#{settings.prettyLink + "/" + v.url + (v.otherid === null ? "" : "/" + v.otherid)}/",
        class="Box #{i == view.start ? "Batch" : ""}",
        title="Click to view the #{v.name}"
    )
        img(src="#{settings.siteUrl}images/thumb/#{v.image}", alt="The #{v.name}")
        span #{v.name}
- }

如何执行$data[$html] = ob_get_clean();行? (也可能是json_encode一个,虽然我现在对JSON.stringify寄予厚望。:)

编辑在@loganfsmyth请求时,用于呈现Jade文件的代码(基本上与Express示例相同)。

res.render("search", { view: view, settings: vgSettings.app });

2 个答案:

答案 0 :(得分:5)

没有尝试过,但是从Express docs开始,这个应该工作:

res.render('yourJadeView', { someOptionalLocal: 'someValue' }, function(err, string) {
    res.json({html: string});
});

答案 1 :(得分:0)

如果您只想输出JSON,这应该可以完成这项工作:

    res.json({ yourValue: 'hi there' });

可以添加状态代码:

    res.json(obj, status) 

例如:

    res.json( { workouts: docs }, 200);  

或者,地点可以交换,如:

    res.json(status, obj);

使用res.json时,无需指定标头或调用.end()。它将默认执行所有操作。