简体   繁体   English

如何让外部JSON用于Jade从Express渲染?

[英]How to let external JSON for Jade to render from Express?

I am a beginner for Node / Express, I would like to use Jade and Express to serve my static files. 我是Node / Express的初学者,我想使用Jade和Express服务我的静态文件。

Previously I use Jade with combination of gulp-jade and gulp-data, I would be able to render the Jade files and use gulp-data which has JSON files to render each page. 以前,我将Jade与gulp-jade和gulp-data结合使用,我将能够呈现Jade文件并使用具有JSON文件的gulp-data呈现每个页面。

index.jade + index.json would give me an output of index.html index.jade + index.json将给我index.html的输出

Now I am having a trouble on how to include my external JSON files to Jade using Express. 现在,我在如何使用Express将外部JSON文件包括到Jade中时遇到了麻烦。

for example: 例如:

server.js server.js

app.get('/', function(req, res){
    res.render('pages/index', {pagetitle: 'Hello World'});
});

pages/index.jade 页/ index.jade

h2 #{pagetitle}

this would render to 这将导致

<h2>Hello World</h2>

Problem 问题

I would like to replace {pagetitle: 'Hello World'} to an external json file which is index.json. 我想将{pagetitle: 'Hello World'}替换为外部json文件,即index.json。 Can I do that? 我可以这样做吗?

app.get('/', function(req, res){
    res.render('pages/index', 'folder_name/index.json');
});

It's definitely wrong, right? 肯定是错的,对吧?

Yes, this is wrong. 是的,这是错误的。 This will set the string itself as the model. 这会将字符串本身设置为模型。 You may want to take a look at the fs module of NodeJS. 您可能需要看一下NodeJS的fs模块。 This will allow you to read the content of the file. 这将使您可以读取文件的内容。 You may then parse the JSON and send the resulting object as the model to your jade template. 然后,您可以解析JSON并将结果对象作为模型发送到您的Jade模板。

Don't forget to read your JSON asynchronously or you'll block your server. 不要忘记异步读取JSON,否则您将阻塞服务器。

https://nodejs.org/api/fs.html https://nodejs.org/api/fs.html

The next step would be to create a module responsible to read this file, keep it in memory and only reload it when it changed using a watcher. 下一步将是创建一个负责读取此文件的模块,将其保存在内存中,并仅在使用观察程序进行更改时才重新加载它。

Thanks for the help @gretro. 感谢您的帮助@gretro。

I was able to fix my issue with your help. 在您的帮助下,我能够解决我的问题。

Here's my solution: 这是我的解决方案:

var renderFromJson = function(json_path, renderTemplate) {
    fs.readFile(json_path, function(err, data) {
        renderTemplate(JSON.parse(data));
    })
}

app.get('/', function(req, res){
    renderFromJson('datas/index.json', function(json_data) {
        res.render('pages/index', json_data);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM