【问题标题】:How can I pass variable to ejs.compile如何将变量传递给 ejs.compile
【发布时间】:2013-03-04 12:34:13
【问题描述】:

我的 bottom_index.ejs 看起来像这样:

<div>The bottom section</div>

在我的代码中我声明了 ejs:

ejs = require('ejs');

然后编译函数:

var botom_index_ejs =
ejs.compile(fs.readFileSync(__dirname + "/../views/bottom_index.ejs", 'utf8'));

然后调用它来获取渲染的html:

botom_index_ejs()

效果很好!

现在我想将我的模板更改为:

<div><%= bottom_text %></div>

并且能够将参数(bottom_text)传递给bottom_index.ejs

应该如何传递参数?

谢谢!

【问题讨论】:

    标签: node.js ejs


    【解决方案1】:

    参数作为 JS 普通对象传递给 EJS 模板。对于您的示例,它应该是:

    botom_index_ejs({ bottom_text : 'The bottom section' });
    

    更新:

    test.js

    var fs = require('fs');
    var ejs = require('ejs');
    var compiled = ejs.compile(fs.readFileSync(__dirname + '/test.ejs', 'utf8'));
    var html = compiled({ title : 'EJS', text : 'Hello, World!' });
    console.log(html);
    

    test.ejs

    <html>
        <head>
            <title><%= title %></title>
        </head>
        <body>
            <p><%= text %></p>
        </body>
    </html>
    

    【讨论】:

    • 我试过了,但没有定义bottom_text。你能举一个小的工作 Hello world 例子吗?使用“编译”功能对我来说很重要,而不仅仅是任何可行的解决方案。谢谢。
    猜你喜欢
    • 2021-05-25
    • 2018-12-28
    • 2011-04-12
    • 2017-01-24
    • 2018-05-17
    • 2012-04-20
    • 2018-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多