微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在带有express.js和lodash / underscore的模板文件中包含一个页脚?

我有一个html文件footer.html,它存储了网站的页脚,我想在不同的页面上重用它.如何将其包含在带有lodash / underscore的模板文件template.html中?我已经阅读了这个关于node-partial的article,但是我不确定模块node-partial如何在Express 4中使用render.

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

模板文件

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

解决方法:

是的,但您需要退出一点,并将页脚添加为有效负载的一部分.

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支持它.

在jade中,您将创建名为footer.pug和index.pug的文件.要在页面中包含页脚,它将是:

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

注意:在pug 2.0中,#{}语法将替换为${},以便与ES6模板字符串语法更加一致

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐