Red*_*ant 3 javascript node.js express underscore.js lodash
我有一个html文件footer.html存储网站的页脚,我想在不同的页面上重用它.如何template.html使用lodash/underscore 将其包含在模板文件中?我已阅读本文章有关node-partial,但我不知道怎么模块node-partial可以与工作render在快递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 !'})
});
Run Code Online (Sandbox Code Playgroud)
Template file
<h1><%= hello %></h1>
<p><%= _('hello') %></p>
<% include './footer.html' %> // Can I add a footer file to the template?
Run Code Online (Sandbox Code Playgroud)
是的,但您需要退出一点,并将页脚添加为有效负载的一部分.
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)
});
Run Code Online (Sandbox Code Playgroud)
-
<h1><%= hello %></h1>
<p><%= _('hello') %></p>
<%=footer%>
Run Code Online (Sandbox Code Playgroud)
或者,您可以切换到更强大的模板语言.PUG是一种语言,Express.js默认支持它.
在jade中,您将创建名为footer.pug和index.pug的文件.要在页面中包含页脚,它将是:
h1 ${hello}
p ${hello}
include footer
Run Code Online (Sandbox Code Playgroud)
注意:在pug 2.0中,#{}语法被替换${}为与ES6模板字符串语法更加一致
| 归档时间: |
|
| 查看次数: |
1526 次 |
| 最近记录: |