2013-04-02 28 views
0

我是一個初學者的節點,只是想使用Jade模板引擎,我讀了GitHub頁面上的ReadMe,並且我最終認爲這應該是工作:試圖瞭解如何使用Jade與Node.js

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

但它不,可能有人向我解釋什麼,我做錯了什麼?非常感謝!

+0

這不是autamagic,你必須在迴應中編寫玉石 –

回答

0

這行代碼:

fn; 

…不調用fn。它檢索變量fn中的值,然後丟棄它,而不用做任何事情。相反,你怎麼稱呼它,然後用它的返回值作爲參數傳遞給res.end

res.end(fn()); 

此外,html p hello不會做你認爲它的作用:它認爲你想有一個標籤,html,與文本p hello在裏面。這不是你想要的。您需要使用新行和正確的壓痕,然後它會工作:

html 
    p hello 

順便說一句,如果你要使用玉,你可能想沒有那個外來

res.write("Hello World!"); 
+0

感謝您的回覆,這有效!在準備就緒後,我會在一分鐘之內選擇答案,是的,你好世界只是爲了確保服務器正在運行 – Datsik

2

玉需要適當的換行符才能工作。適當的換行符在內聯javascript中很難看。 (另外,使用Jade進行模板化的好處是分離關注點,例如代碼中沒有視圖邏輯)。

要做到這一點,最簡單的辦法是你的模板文件中的隔離:

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.'); 
+0

__dirname做什麼?和漂亮:? – Datsik

+0

@XCritics,'pretty'告訴Jade產生漂亮的縮進輸出。 __dirname是node.js中的一個全局變量,它引用運行腳本位於的當前目錄:http://nodejs.org/docs/latest/api/globals.html#globals_dirname – methai