res.render()前端上的本地位置 [英] res.render() Locals Location on Frontend

查看:301
本文介绍了res.render()前端上的本地位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是在Express中,当您在 res.render(view,{variable:variable})中定义局部变量时,如何访问它们在前端?他们住在哪里?当我尝试访问通过 console.log(variable)通过此方法定义的变量时,Firebug抛出错误,指出 variable 未定义。我还尝试了 console.log(window.variable),结果相似。那么这些变量保存在哪里?

This is probably a stupid question, but in Express, when you define local variables in res.render(view, {variable: variable}), how are they accessed on the frontend? Where are they kept? When I try to access a variable I defined through this method with console.log(variable) Firebug throws an error saying that variable is not defined. I also tried console.log(window.variable), with similar results. So where are these variables kept?

此外, res.locals 变量是否保存在同一位置?他们只是扔出去?这些变量可供模板引擎使用,例如 swig jade ,但我无法使用 console.log()。

Also, are res.locals variables kept in the same place, or are they just thrown out? These variables are accessible to templating engines like swig and jade, but I could not find them using console.log() either.

推荐答案

这些变量不会自动传递给客户端码;如您所说,它们可以在您的视图模板中进行编码。同样,以及在 res.locals (或 app.locals (具有相同的API)可以在任何视图中用作局部变量。

These variables are not passed automatically to client-side code; as you say, they're available to code in your view templates. Similarly, and variables defined in res.locals (or app.locals, which has the same API) will be available as local variables in any views.

如果要将它们提供给客户端代码,则必须手动将它们作为响应的一部分发送给客户端,以客户端可访问的形式发送JavaScript。例如,您可以将它们写入< script> 标记,如此处所示:在客户端JavaScript中访问Express.js本地变量

If you want to make them available to client side code, you'd have to manually send them as part of the response, in a form accessible to the client-side JavaScript. For instance, you could write them to a <script> tag, as is done here: Accessing Express.js local variables in client side JavaScript .

这篇关于res.render()前端上的本地位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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