节点JS模板将对象添加到窗口

时间:2021-01-24 22:02:05

I was wondering if there was a way, when rendering a javascript template with Node, to attach an object or values to the window object. For example, if I wanted to take the data that was passed to the res.render function and attach it to the window object for later use. Later use would be for hash routing. Currently I am using Nunjucks.

我想知道在使用Node渲染javascript模板时是否有办法将一个或多个对象附加到窗口对象。例如,如果我想获取传递给res.render函数的数据并将其附加到窗口对象以供以后使用。稍后使用将用于散列路由。目前我正在使用Nunjucks。

res.render('index', {data:{name:'Max'}});
// How could  I attach data to the window object for later use.

Any other suggestions would be appreciated.

任何其他建议将不胜感激。

EDIT: I didn't make this clear, but when I was referring the the window object, I was referring to the client window object. Not a window object in Node. When rendering the template how can I add items to the window object.

编辑:我没有说清楚,但当我引用窗口对象时,我指的是客户端窗口对象。不是Node中的窗口对象。渲染模板时,如何向窗口对象添加项目。

2 个解决方案

#1


You can render an inline script right to the html output:

您可以直接向html输出呈现内联脚本:

<body>
<script>
window.data = {name: 'Max'};
</script>
</body>

But adding properties to global object is not recommended, better use a namespace like:

但是不建议在全局对象中添加属性,最好使用如下命名空间:

var app = {};
app.data = {name: 'Max'};

#2


In node GLOBAL object is equivalent to window object in DOM scripting. Assign it to GLOBAL object. Refer the link below for more info about GLOBAL object in node. http://www.hacksparrow.com/global-variables-in-node-js.html

在节点GLOBAL中,对象相当于DOM脚本中的窗口对象。将其分配给GLOBAL对象。有关节点中GLOBAL对象的更多信息,请参阅以下链接。 http://www.hacksparrow.com/global-variables-in-node-js.html

#1


You can render an inline script right to the html output:

您可以直接向html输出呈现内联脚本:

<body>
<script>
window.data = {name: 'Max'};
</script>
</body>

But adding properties to global object is not recommended, better use a namespace like:

但是不建议在全局对象中添加属性,最好使用如下命名空间:

var app = {};
app.data = {name: 'Max'};

#2


In node GLOBAL object is equivalent to window object in DOM scripting. Assign it to GLOBAL object. Refer the link below for more info about GLOBAL object in node. http://www.hacksparrow.com/global-variables-in-node-js.html

在节点GLOBAL中,对象相当于DOM脚本中的窗口对象。将其分配给GLOBAL对象。有关节点中GLOBAL对象的更多信息,请参阅以下链接。 http://www.hacksparrow.com/global-variables-in-node-js.html