简体   繁体   中英

Trying to understand how to use Jade with Node.js

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!

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, eg 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.');

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!");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM