问题
i've been closing in on a node application using express and ejs, but when i try to hand data to my view from the controller like so
var myData = {
theData: data
};
res.render(path.join(__dirname + '/../views/index'), myData);
i get a nice error
ReferenceError:.. myData is not defined eval (from ejs lib)
when trying to access myData in the view like so
var data = <%-myData%>;
or in any other way basically, i've tried stringifying the data, wrapping it in another object and stuff like that but it still just won't show up, i have the feeling i'm missing something really basic here, does anyone have an idea on how to fix this?
回答1:
The second argument you pass to render()
is an object containing the view variables you want to use in your template. So the error you are seeing makes sense. If you want to use myData
in that way you'd have to do something like this in your controller/app:
res.render(..., { myData: JSON.stringify(myData) });
回答2:
There's a silly mistake I make when I try to send data from the server. Here's the mistake: var data = <%=myData%>; What you should do when passing it: var data = <%-myData%>; It's supposed to be a dash NOT an equal before the variable name.
回答3:
If your are generating the template with the HtmlWebpackPlugin plugin, the data should be passed in your webpack configuration file, along with the templateParameters
property.
For example:
...
plugins: [
new HtmlWebpackPlugin({
filename: __dirname + "/src/views/index.ejs",
template: "./src/views/index_template.ejs",
templateParameters: {
myData,
},
}),
],
...
来源:https://stackoverflow.com/questions/27278565/node-ejs-reference-error-data-not-defined-at-eval-when-handing-data-to-view