Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static javascript not rendering in jade (with express/node.js)

I hope you are well.

I'm suddenly unable to render any external javascript in jade templates! To get to the bottom of things, I stripped it down to the bare minimum :

Node 0.6.11, Express 2.5.8, jade 0.20.3

app.js

var express = require('express')
, routes = require('./routes');

var app = module.exports = express.createServer();

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});

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

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

app.get('/', function(req, res){
  res.render('index', { title: 'Express' });
});

app.listen(3000);

layout.jade

!!!
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(type='text/javascript', src='/javascripts/script.js')
  body!= body

script.js

alert('hello!');

It seems to me that when I run the server and load http://localhost:3000/, I should straightaway get a 'hello!' message, but it just runs straight to the normal page. What's more, if I manually type

script
  alert('hello!')

into the layout.jade template I get the message just as I should. It is just not loading the static script. And I have certainly checked that 'script.js' is in '/public/javascripts/' just as it should be. Any advice would be very welcome!!!

Thanks in advance

like image 494
Petrov Avatar asked Dec 04 '22 04:12

Petrov


1 Answers

you need to pass your script from the controller like that:

app.get('/', function(req, res){
  res.render('index', { title: 'Express', scripts: ['javascripts/script.js']});
});

and then in your head in layout.jade:

- each s in scripts
    script(src=s)
like image 143
plus- Avatar answered Dec 24 '22 07:12

plus-