sobremesa sobremesa - 5 months ago 26
Node.js Question

How to pass variable from jade template file to a script file?

I'm having trouble with a variable (config) declared in a jade template file (index.jade) that isn't passed to a javascript file, which then makes my javascript crash. Here is the file (views/index.jade):

h1 #{title}

script(src='./socket.io/socket.io.js')
script(type='text/javascript')
var config = {};
config.address = '#{address}';
config.port = '#{port}';
script(src='./javascripts/app.js')


Here is a part of my app.js (server side):

app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
app.set('address', 'localhost');
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
app.use(express.errorHandler());
});

// Routes

app.get('/', function(req, res){
res.render('index', {
address: app.settings.address,
port: app.settings.port
});
});

if (!module.parent) {
app.listen(app.settings.port);
console.log("Server listening on port %d",
app.settings.port);
}

// Start my Socket.io app and pass in the socket
require('./socketapp').start(io.listen(app));


And here is a part of my javascript file that crashes (public/javascripts/app.js):

(function() {
var socket = new io.Socket(config.address, {port: config.port, rememberTransport: false});


I'm running the site on development mode (NODE_ENV=development) on localhost (my own machine). I'm using node-inspector for debugging, which told me that the config variable is undefined in public/javascripts/app.js.

Any ideas?? Thanks!!

Answer

It's a little late but...

script.
  loginName="#{login}";

This is working fine in my script. In Express, I am doing this:

exports.index = function(req, res){
  res.render( 'index',  { layout:false, login: req.session.login } );
};

I guess the latest jade is different?

Merc.

edit: added "." after script to prevent Jade warning.

Comments