javascript - 如何从大型 json 对象中获取特定数据到 Jade mixin 中

标签 javascript json node.js pug

这是来 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 use var 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)

渲染结果如下:

rendering from mixin

此外,Jade 现在是 Pug,我知道您知道,既然您在这个问题中标记了 Pug,您应该开始将其引用为 Pug:)。

关于javascript - 如何从大型 json 对象中获取特定数据到 Jade mixin 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44479143/

相关文章:

javascript - 我如何以部分方式显示 json

ios - NSURLSession 中的 "Type of expression is ambiguous without more context"

javascript - 从平面数组创建嵌套对象

javascript - NodeJS - 如何在不使用外部数据库的情况下管理用户名和任务管理?

javascript - 如何在 api 的链式执行期间制作 frisby.js 脚本 "pause"

javascript - Angular switch 语句根据响应代码执行不同的操作

javascript - Jquery 字符串连接

javascript - Express - 在单个请求中向浏览器发送页面和自定义数据?

javascript - 下拉菜单滚动条问题

javascript - EventEmitter 是否只是将函数映射到对象中?