Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a variable from jade to javascript

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

express route that fetches home page is:

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 the following:

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 that looks like the following:

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

Problem: The console prints:

"!{_ajaxData}" 

where I am looking to get the full array passed to the javascript.

Appreciate any insights

like image 685
Kiran Avatar asked Jan 21 '14 16:01

Kiran


People also ask

What is $$ in JavaScript?

$ and $$ are valid variable names in JavaScript, they have no special meaning. Usually they set their value to library instances, in your example if you check the closure call, at the end of the file you'll see that $ is jQuery in this case if it is defined and $$ is cytoscape.

How do I transfer data from one JavaScript to another?

There are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.

What is Jade in JavaScript?

Jade is a template engine for node. js and the default rendering engine for the Express web framework. It is a new, simplified language that compiles into HTML and is extremely useful for web developers. Jade is designed primarily for server-side templating in node.


1 Answers

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

like image 197
bzupnick Avatar answered Nov 03 '22 10:11

bzupnick