这是来 self 的服务器的 json:
data = {"id":393, "state":"mississippi", "lat":null, "lng":null, "title":"someTitle", "country":null};
然后我将其通过 Jade 寺传递,如下所示:res.render('editUpload', {fromServer:data});
然后在我的 Jade 模板中我有这个:
var data = !{fromServer};
console.log(data.address);
正确打印密西西比州
但是,我正在尝试让我的 mixin 使用该数据
混合:
mixin textBoxMixin(name, label, value)
div(style="display:flex; width:100%;")
span.label #{label}
input(type="text", name="#{name}", value="#{value}")
然后我像这样使用它:
+textBoxMixin("title", "Title", fromServer)
用整个 json "{"id":393, "state":"mississippi", "lat":null, "lng":null, "title":"someTitle", "填充文本框Country":null}"所以我去尝试一下:
+textBoxMixin("title", "Title", fromServer.title)
它打印“未定义”。
如何让这个 mixin 接受应该是 fromServer.title
的内容?
我尝试过 JSON.stringify(fromServer)、data.address (这显然不起作用,因为数据在页面渲染期间未定义)。我知道我可以返回我的服务器并解析那里的所有 json 并将每个项目作为单独的项目传递,但这将是一个巨大的痛苦,因为我的 json 实际上比我在这里发布的要大得多。 p>
The problem was that I was sending the json from the route.js file to the template after having passed it through
JSON.stringify()
, this let me usevar data = !{fromServer};
in the page's scripts, but Jade couldn't parse the String. So now I'm doing this in the route so that I have both the json available for templating and the String for JavaScript:
data = rows[0][0];
stringFromServer = JSON.stringify(rows[0][0]);
res.render('editUpload', {fromServer:data, stringFromServer:stringFromServer, username: req.session.user});
最佳答案
当您在 mixin 定义中引用参数时,您可以像正常的 pug 代码一样传递它们,不带引号和大括号。
mixin textBoxMixin(name, label, value)
div(style="display:flex; width:100%;")
span.label= label
input(type="text", name=name, value=value)
+textBoxMixin("title", "Title", fromServer.title)
渲染结果如下:
此外,Jade 现在是 Pug,我知道您知道,既然您在这个问题中标记了 Pug,您应该开始将其引用为 Pug:)。
关于javascript - 如何从大型 json 对象中获取特定数据到 Jade mixin 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479143/