Include footer in template file with express.js and lodash / underscore?

I have an html file footer.html

that stores the footer of a website and I would like to reuse it across different pages. How can I include it in a template file template.html

using lodash / underscore? I've read this article about node-partial

, but I'm not sure how the module node-partial

might 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?

      

+3


source to share


1 answer


Yes, but you need to backtrack a bit and add a 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 can switch to a more powerful templating language. PUG is such a language and it is supported by default by Express.js.

in jade you will create files named footer.pug and index.pug. To add a footer to the 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

+6


source







All Articles