简体   繁体   中英

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.

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.

index.jade + index.json would give me an output of index.html

Now I am having a trouble on how to include my external JSON files to Jade using Express.

for example:

server.js

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

pages/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. 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. 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.

Don't forget to read your JSON asynchronously or you'll block your server.

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.

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);
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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