【问题标题】:How can I use data passed into jade template in the views javascript?如何在视图 javascript 中使用传递给玉模板的数据?
【发布时间】:2016-08-29 04:03:49
【问题描述】:

将数据渲染到模板res.render('account/pets/allPets', { petMap, title: 'All Pets' }) 我尝试了两件事来完成这项工作

一)

        var neighborhoods = [];
        for (var i = 0; i < petMap.length; i++) {
         neighborhoods.push(new google.maps.LatLng(petMap[i].location.loc[0],pet.location.loc[1]))
        }

B)

    var neighborhoods = [
    each pet in petMap
      new google.maps.LatLng(petMap[i].location.loc[0],pet.location.loc[1])
    ]

【问题讨论】:

    标签: javascript node.js pug


    【解决方案1】:

    假设 patMap 是一个 javascript 对象,您需要做一些 hacky 的事情来完成这项工作。 Pug 渲染服务器端,而 javascript 在客户端,所以你不能直接访问 JS 中的 pug 变量。你可以做的是在pug编译时将你的js对象转换为字符串,然后在客户端执行时将其解析为JSON。

    var petMap = JSON.parse(("#{JSON.stringify(petMap)}").replace(/&quot;/g, '"'));
    /*
        Let me break this down in terms of execution
        "#{JSON.stringify(petMap)}" -> executes server side, converts #{} accesses pug variable petMap, which has been converted to an object
        .replace(/&quot;/g, '"') -> replaces quote escape sequences (something html does for security) back to quotes so JSON can be parsed
        JSON.parse -> parses json from stringified json the server sent to the client
    */ 
    

    【讨论】:

    • 我偶然发现了这个答案,它看起来很笨拙而且有点凌乱,所以我最终将数据属性添加到我的列表项中,然后我能够将它们放在地图上并从那里添加过滤器。为我工作li.in(data-location=pet.location.loc, data-address=pet.location.name, data-name=pet.name, data-img=pet.picture, data-id=pet._id)感谢您的回复和良好的解释。
    猜你喜欢
    • 2011-02-20
    • 2012-10-09
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2010-11-07
    相关资源
    最近更新 更多