【问题标题】:Include a footer in a template file with express.js and lodash/underscore?在带有 express.js 和 lodash/underscore 的模板文件中包含页脚?
【发布时间】:2014-12-20 08:31:13
【问题描述】:

我有一个 html 文件 footer.html 存储网站的页脚,我想在不同的页面上重复使用它。如何使用 lodash/underscore 将其包含在模板文件 template.html 中?我已经阅读了这篇关于node-partialarticle,但我不确定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 !'})
});

Template file

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

【问题讨论】:

    标签: javascript node.js express underscore.js lodash


    【解决方案1】:

    你可以。您需要后退一点并将页脚添加为有效负载的一部分。

    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默认支持。

    在 PUG 中,您将创建名为 footer.pug 和 index.pug 的文件。要在索引页中包含页脚,应为:

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

    注意:在 pug 2.0 中 #{} 语法被替换为 ${} 以更符合 ES6 模板字符串语法

    【讨论】:

      猜你喜欢
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 2012-06-18
      • 2011-08-14
      • 1970-01-01
      • 2011-11-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多