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: 'Welcome !'})
});
Template file
<h1><%= hello %></h1>
<p><%= _('hello') %></p>
<% include './footer.html' %> // Can I add a footer file to the template?
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: 'Welcome !', 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With