7

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

1
  • FYI: I realized that browser is fetching the home.js without any processing by express. However, I am still curious to know if there is any better way to do this. Commented Jan 21, 2014 at 16:15

1 Answer 1

22

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

Sign up to request clarification or add additional context in comments.

4 Comments

thanks worked with minor change: script(type='text/javascript') | var local_data =!{JSON.stringify(data)}; script(src='javascripts/myScript.js')
otherwise, its turning var into <var>
You should add . character after the script e.g. script(type='text/javascript'). so that you code is treated as text and not more templating
Jonathan is correct, for reference this changed recently. In older versions jade would understand that anything nested inside a script tag was a js block and not more templating; in recent versions (post 1.0.0 from memory) you need the trailing dot, or the pipe character.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.