简体   繁体   English

Node.js Express和Ejs尝试将变量从js文件传递到ejs文件

[英]Node.js express and ejs trying to pass a variable from js file to ejs file

My folder structure is public-js-color.js and the ejs file is views-index.ejs 我的文件夹结构是public-js-color.js,ejs文件是views-index.ejs

How do I pass a variable from the color.js file into the index.ejs file so I can display it to the user. 如何将变量从color.js文件传递到index.ejs文件,以便可以将其显示给用户。 Please forgive me if this is simple, just learning node and google has been no help. 如果这很简单,请原谅我,只是学习节点和谷歌一直没有帮助。

when you define your express route and call render you want to pass to the view as the second parameter. 当您定义快车路线并调用渲染时,您想作为第二个参数传递给视图。

var variablesToPass = {
  homie: 'who is your homie?'
};

app.get('/', function(req, res) {
  return res.render('index', variablesToPass);
});

You will be able to render homie on your ejs home template by typing <%= homie %> 通过输入<%= homie%>,您将能够在ejs主页模板上呈现homie。

Also if you would like the variables to be available across your entire application a useful middlware function you could create is. 同样,如果您希望变量在整个应用程序中都可用,那么可以创建一个有用的中间件函数。

app.use(function(req, res) {
  res.locals.homie = "I'm a homie thats available everywhere";
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM