0

I am trying to import data from mongodb into jade template, in order to show them in graph. I am using chart.js inline script, in order to render data on graph. So data from Mongodb is on the page, and I can access it like this:

each city in cities
    p #{city.name}

And here is how I pass data to page:

exports.index = function(req,res){
    var cities = City.find({}).limit(20);
    cities.exec(function(err,doc) {
        res.render("index",{cities:doc});
    });
};

I created same app with php, by simply passing data to page and injecting data into javascript graph(with json_encode)

Here is final result with php:

It was easy, since php data are global to HTML page. How to do that with Jade ?

Thanks

Miroslav Trninic
  • 3,327
  • 4
  • 28
  • 51

1 Answers1

2

Ah, so your goal is to both use the city data to generate HTML on the server but ALSO make it available in the browser as raw javascript object data. To do that you format it as JSON and stuff it into a <script> tag. There are modules to help with this such as sharify, but the basic idea in your jade template do something like:

In your express route handler javascript:

exports.index = function(req,res){
    var cities = City.find({}).limit(20);
    cities.exec(function(err,doc) {
        //There are tricky rules about safely embedding JSON within HTML
        //see http://stackoverflow.com/a/4180424/266795
        var encodedCityData = 'window.cities = ' + JSON.stringify(cities)
            .replace(/</g, '\\u003c')
            .replace(/-->/g, '--\\>');
        res.render("index",{cities:doc, encodedCityData: encodedCityData});
    });
};

In your jade template:

script!= encodedCityData

In the browser, you will have access to the data via the cities variable which has been set onto the window object.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274