简体   繁体   English

如何将数组传递给Express中的ejs模板?

[英]How can I pass an array to an ejs template in express?

I'm trying to pass an array which contains objects to views of ejs in express, but it doesn't work. 我正在尝试将包含对象的数组传递给express中的ejs视图,但它不起作用。

In server, 在服务器中

var roominfo = function(roomname){
this.roomname=roomname;
};

room_info_array= new Array(1);
room_info_array[0]=new roominfo("room");

app.get("/", function(req, res){
res.render('login',{room_info:room_info_array});
});

In client, 在客户端,

<script type="text/javascript">
var data = <%= JSON.stringify(room_info) %>
</script>

this shows error "Uncaught SyntaxError: Unexpected token & ". 这显示错误“Uncaught SyntaxError:Unexpected token&”。

var data = [{&quot;roomname&quot;:&quot;room&quot;}]"

I tried this 我试过这个

<script type="text/javascript">
var data = <% JSON.stringify(room_info) %>
</script>

However this shows data is undefined. 但是,这表明数据未定义。

How should I pass the array to ejs correctly? 我应该如何正确地将数组传递给ejs?

In EJS echoing something is done with 在EJS回声中完成了一些事情

<%= %>

or 要么

<%- %>

In the last example you're not echoing anything, so nothing is passed to data and it's undefined. 在最后一个示例中,您没有回显任何内容,因此没有任何内容传递给data ,并且未定义。

In the first example you're also escaping the echoed content, so try using echoing the string unescaped as that will remove the entities. 在第一个示例中,您还要转义回显的内容,因此请尝试使用未转义的字符串回显,因为这将删除实体。

var data = <%- JSON.stringify(room_info) %>

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

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