使用jade迭代页面脚本内部

时间:2013-08-04 11:40:05

标签: javascript node.js iteration

我需要将(json)对象插入到页面中使用的数组中。我正在使用带有jade的nodejs,并假设下面的代码可能符合我的目的,但它不起作用。

    //this code is in the template:
    script.
        otherPlayers = {};
        each player in playerList
           otherPlayers["#{player.playerId}"] = !{JSON.stringify(#{player})};

在页面中,预期结果为:

<script>
    otherPlayers = {};
    otherPlayers[0] = {"playerId": 0, "playerName": "Leo" };
    otherPlayers[1] = {"playerId": 1, "playerName": "Daniel" };
    otherPlayers[2] = {"playerId": 2, "playerName": "Lucas" };
</script>

任何提示都被广泛接受。 提前谢谢。

1 个答案:

答案 0 :(得分:2)

您可以在模板文件中执行以下操作。

//In the template file
script.
    otherPlayers = {};
    var cplayerList = !{JSON.stringify(playerList)};
    for(player in cplayerList) {
        otherPlayers[cplayerList[player].playerId] = cplayerList[player];
    }
    console.log(otherPlayers);