如何在视图javascript中使用传递到jade模板的数据?

时间:2016-08-29 04:03:49

标签: javascript node.js pug

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

A)

        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])
    ]

1 个答案:

答案 0 :(得分:0)

假设patMap是一个javascript对象,你需要做一些hacky事情才能使它工作。 Pug渲染服务器端,而客户端上的javascript,所以你不能直接访问JS中的pug变量。 CAN 做的是在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
*/