最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Include a footer in a template file with express.js and lodashunderscore? - Stack Overflow

programmeradmin1浏览0评论

I have a html file footer.html that stores a footer of the website and I'd like to reuse it on different pages. How can I include it in the template file template.html with lodash/underscore? I have read this article about node-partial but I'm not sure how the module node-partial could work with render in Express 4.

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: 'Wele !'})
});

Template file

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

I have a html file footer.html that stores a footer of the website and I'd like to reuse it on different pages. How can I include it in the template file template.html with lodash/underscore? I have read this article about node-partial but I'm not sure how the module node-partial could work with render in Express 4.

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: 'Wele !'})
});

Template file

<h1><%= hello %></h1>
<p><%= _('hello') %></p>
<% include './footer.html' %> // Can I add a footer file to the template?
Share Improve this question edited Dec 20, 2014 at 9:30 RedGiant asked Dec 20, 2014 at 8:31 RedGiantRedGiant 4,76911 gold badges63 silver badges151 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8 +50

You can. You need to back out a little bit and add the footer as part of the payload.

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: 'Wele !', footer: footerHTML)
});

--

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

Alternatively, you could switch to a more powerful templating language. PUG is such a language, and it is supported by default by Express.js.

in PUG you would create files named footer.pug and index.pug. To include the footer in your index page it would be:

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

Note: in pug 2.0 the #{} syntax is replaced with ${} to be more consistent with ES6 template string syntax

发布评论

评论列表(0)

  1. 暂无评论