如何在node.js ejs模板中将变量从后端传递到前端 [英] How to pass variable from back-end to front-end in node.js ejs template

查看:38
本文介绍了如何在node.js ejs模板中将变量从后端传递到前端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样渲染我的页面:

response.render('index', {
    data: list // the `list` is an array variable
});

在首页中,我想将 data 存储为Globe变量,所以我尝试了:

And in the front page, I want store the data as globe variable, so I tried:

<script>
   window.app = <%= data %>
</script>

但结果是:

window.app = [object Object],[object Object],[object Object]

那我该怎么做呢?

推荐答案

您可以将数据字符串化为JSON,它是javascript的子集,将被解析为确切的数据结构.还要使用<%-表达式%> 来确保您的JavaScript不会被转义.

You can stringify the data as JSON, which is a subset of javascript, and will be parsed as the exact data structure. Also use <%- expression %> to make sure your javascript won't be escaped.

<script>
   window.app = <%- JSON.stringify(data) %>
</script>

请注意,这将不包含函数,并且会抛出循环数据结构.但是类似 [{{a:{b:3}}] 之类的东西应该可以正常工作.日期也将转换为字符串.

Note that this won't include functions and it will throw on cyclic data structures. But stuff like [{ a : { b : 3 }}] should work fine. Dates are also converted to strings.

这篇关于如何在node.js ejs模板中将变量从后端传递到前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆