【问题标题】:Ejs engine with html not working带有html的Ejs引擎无法正常工作
【发布时间】:2013-09-16 05:04:30
【问题描述】:

我用的是html文件而不是ejs,但是express引擎是ejs

views
|
|--header.html
|--footer.html
|
|--index.html

我是这样配置的

app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);  

我通过这个渲染我的index 模板:

res.render('index.html', {title: 'test'});

但是如何在 index.html 中包含 header 和 footer.html

类似的帖子 Node.js express: confuse about ejs template

不工作的现有示例 https://github.com/visionmedia/express/tree/master/examples/ejs

【问题讨论】:

    标签: node.js express ejs


    【解决方案1】:

    您所要求的原始方法是使用部分。部分已被删除,并替换为 EJS 的 include 函数。这是包含文件的方式:

    <% include header.html %>
    <% include footer.html %>
    

    您传递给渲染页面的任何本地变量也将传递给包含。例如:

    app.js

    app.get('/', function(req, res) {
      res.render(__dirname + '/index.html', {
        string: 'random_value',
        other: 'value'
      });
    });
    

    index.html

    <!DOCTYPE html>
    <body>
      <%= other %>
      <% include content.html %>
    </body>
    

    content.html

    <pre><%= string %></pre>
    

    你会得到的 HTML 是:

    <!DOCTYPE html>
    <body>
      value
      <pre>random_value</pre>
    </body>
    

    【讨论】:

    • 谢谢你的回复,我试过了,还是不行。应用程序配置应该如何?她是我的代码link
    • 它对你有用吗,我收到类似SyntaxError: Unexpected identifier at Object.Function (&lt;anonymous&gt;) at exports.compile (C:\workspace\ejs_html\node_modules\ejs\lib\ejs.js:209:12) at Object.exports.render (C:\workspace\ejs_html\node_modules\ejs\lib\ejs.js:245:10) at View.exports.renderFile [as engine] (C:\workspace\ejs_html\node_modules\ejs\lib\ejs.js:275:22) at View.render (C:\workspace\ejs_html\node_modules\express\lib\view.js:76:8) at Function.app.render的错误
    • 尝试重新安装或更新您的模块。
    • 我的错,我更新到 ejs 0.8.4 版本并且工作正常。非常感谢
    • 有没有办法让你不必包含__dirname
    猜你喜欢
    • 1970-01-01
    • 2019-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多