passing a variable from jade to javascript

11,793

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

Share:
11,793
Kiran
Author by

Kiran

Updated on June 08, 2022

Comments

  • Kiran
    Kiran almost 2 years

    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