2012-04-12 52 views
12

我想了解Express和Jade的工作原理。鏈接到其他玉文件

首先,我是否正確使用layout.jade作爲模板文件(header,body,footer)並使用不同的文件在主體中顯示信息(請參閱下面的示例)?

該代碼工作正常,但我不確定這是否是在Express中執行某些操作的正確方法。如果我應該繼續使用這個結構,我怎麼能從內部鏈接到其他文件(例如,about.jade),例如index.jade,以顯示該文件而不是index.jade?

在此先感謝!

layout.jade:

!!! 5 
html 
    head 
    title= title 
    link(rel='stylesheet', href='/stylesheets/style.css') 
    script(type='text/javascript', src='https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js') 
    script(type='text/javascript', src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js') 
    script(type='text/javascript', src='/javascripts/external.js') 

    // Header 
    header#header 

    // Navigation 
    nav#nav 
    // Navigation code (ul, li etc)... 

    // Sidebar 
    aside#sidebar 
    // Sidebar code... 

    // Body 
    body!= body 

index.jade:

!!! 5 
html 
    head 
    title= title 

    section#wrapper 
     img.imageStyle(src = '/images/test1.png') 
     // And so on... 

About.jade:

// You get it... 

回答

13

我想你要尋找的是視圖渲染路線快遞: http://expressjs.com/en/guide/using-template-engines.html

所以,你可以設置是這樣的:

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

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

從一個鏈接到其他,一旦你配置正確的路線,你可以這樣做:

a(href='/') index 

a(href='/about') about 

更新另外,您不需要再次在索引中重複此操作。

!!! 5 
html 
    head 
    title= title 
+0

很好的答案,謝謝! – holyredbeard 2012-04-13 06:47:34

4

除了Wes Freeman寫的你還可以在你的玉文件中包含其他的玉模板。

這樣你可以有你的header.jade,footer.jade並將它們包含在你的about.jade文件中。這裏是從玉包括文檔: https://github.com/visionmedia/jade#a13

這樣你只需要改變header.jade文件,如果你添加例如應該在每個頁面上的腳本或樣式表標籤。

+0

+1,也是有用的信息。 – 2012-04-13 17:39:19