Reputation: 14824
I'm a beginner to node, just trying to use the Jade template engine, I read the ReadMe on the github page, and I ended up with the idea that this should work:
var http = require('http'),
jade = require('jade'),
fn = jade.compile('html p hello');
function onRequest(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write('Hello World!');
fn;
res.end();
}
http.createServer(onRequest).listen(8888);
console.log('Server started.');
But it does not, could somebody explain to me what I am doing wrong? Thanks a lot!
Upvotes: 0
Views: 390
Reputation: 9133
Jade needs proper line breaks to work. And proper line breaks are ugly in inline javascript. (Plus, the benefit of templating with Jade is the separation of concerns, e.g. no view logic in your code).
The easiest way to do this is to isolate your template in a file:
tpl.jade
doctype 5
html
body
p hello
index.js
var http = require('http')
, jade = require('jade')
, path = __dirname + '/tpl.jade'
, str = require('fs').readFileSync(path, 'utf8')
, fn = jade.compile(str, { filename: path, pretty: true });
function onRequest(req, res) {
res.writeHead(200, {"Content-Type": "text/html"});
res.write(fn());
res.end();
}
http.createServer(onRequest).listen(8888);
console.log('Server started.');
Upvotes: 2
Reputation: 128991
This line of code:
fn;
…does not call fn
. It retrieves the value in the variable fn
and then discards it, without doing anything with it. Instead, you want to call it and then use its return value as an argument to res.end
:
res.end(fn());
Furthermore, html p hello
does not do what you think it does: It thinks you want a tag, html
, with the text p hello
in it. That's not what you want. You need to use newlines and correct indentation, and then it'll work:
html
p hello
By the way, if you're going to use Jade, you may want to not have that extraneous
res.write("Hello World!");
Upvotes: 0