Passing a variable from jade to javascript

I am trying to pass a variable from a route handler to a javascript file.

express route that selects the home page:

exports.home = function(req, res){ var _ajaxData = [ ["#collections","collections", "Collections"], ["#candidates","candidates", "Candidates"], ["#entries","entriess", "Entries"], ["#exits","exits", "Exits"] ]; res.render('home/home', { title: 'Welcome to My Web', _ajaxData: _ajaxData}); }; 

And my jade file looks like this:

 extends ../layout/base block content each item in _ajaxData div(id= item[0]).col-md-6 h3.panel-title= title .panel-body | Loading content... script(src='js/home.js') 

And the content is loaded using ajax in home.js, which looks like this:

 var ajaxData = JSON.stringify('!{_ajaxData}'); console.log(ajaxData); // Further processing here 

Problem: console prints:

 "!{_ajaxData}" 

where I want to get the full array passed by javascript.

Appreciate any ideas

+7
json javascript pug express
source share
1 answer

Add this to your jade file

 script(type='text/javascript') var local_data =!{JSON.stringify(data)}; script(src='javascripts/myScript.js') 

All your data should now be in local_data for your use in myScript.js

+21
source share

All Articles