node.js - 如何将变量传递给 ejs.compile

标签 node.js ejs

我的 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

应该如何传递参数?

谢谢!

最佳答案

参数作为 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>

关于node.js - 如何将变量传递给 ejs.compile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15201724/

相关文章:

javascript - 更新/删除 Node js中的注释

javascript - ejs 页面中未定义relativeTime() 实用程序

javascript - Discord.js 获取 channel 中所有消息的数组

javascript - 本地 EJS 函数不读取变量

node.js 简单项目 : ReferenceError: <ClassName> is not defined

javascript - NodeJS Express Post 表单 - 操作始终为 404

javascript - 将现有项目推送到新创建项目的嵌套数组中

javascript - app.post 无法在 Node.js 上多次运行

node.js - 如何在不使用 npm install <package_name> 或 yarn install 的情况下安装/下载软件包

javascript - 为什么这个简单的 ping pong socket.io 示例在短时间内就失败了? (数据负载未定义)