2014-12-20 36 views
3

我有一個html文件footer.html,它存儲了網站的頁腳,我想在不同的頁面上重複使用它。我如何使用lodash /下劃線將它包含在模板文件template.html中?我已閱讀本articlenode-partial,但我不知道怎麼模塊node-partial可以在快遞4.在express.js和lodash /下劃線的模板文件中包含頁腳?

var express = require('express') 
, app = express() 
, http = require('http').createServer(app) 
, _ = require('lodash')._ 
,cons = require('consolidate'); 

app.engine('html', cons.lodash); 
app.set('view engine', 'html') 
app.set('views', './views') 

app.get('/', function(req, res){ 
    res.render('index.html', {hello: 'Welcome !'}) 
}); 

Template file

<h1><%= hello %></h1> 
<p><%= _('hello') %></p> 
<% include './footer.html' %> // Can I add a footer file to the template? 

回答

6

是與render工作,但你需要背出一點點位,並添加頁腳作爲有效負載的一部分。

var footerHTML; 
fs.readFile("./footer.html", function(err, data){ 
    if (err) return console.error(err); 
    footerHTML = data; 
}) 

app.get('/', function(req, res){ 
    res.render('index.html', {hello: 'Welcome !', footer: footerHTML) 
}); 

-

<h1><%= hello %></h1> 
<p><%= _('hello') %></p> 
<%=footer%> 

或者,您可以切換到更強大的模板語言。 PUG就是這樣一種語言,Express.js默認支持。

在翡翠中,您將創建名爲footer.pug和index.pug的文件。要在您的索引頁的頁腳這將是:

h1 ${hello} 
p ${hello} 
include footer 

注:帕格 2.0 #{}語法替換${}要與ES6模板字符串語法更加一致

+1

鏈接現在HTTP ://jade-lang.com/ –