JSON.parse() in Swig (Node.js)?

空扰寡人 提交于 2019-12-12 20:20:35

问题


I'm trying to switch from Jade to Swig (lured by Swig's insane performance) as my Express template engine when I got stuck here — I'm sending an array of serialized JSON from Express into Swig and retrieve the data in Swig using this loop here:

<ul id = "list">
    {% if items %}
        {% for item in items %}
            {{ JSON.parse( item ).title }}
        {% endfor %}
    {% endif %}
</ul>

... but I get this:

SyntaxError: Unexpected token )
    at Object.Function (unknown source)
    at createTemplate (/home/vijay/node_modules/swig/index.js:72:14)
    at getTemplate (/home/vijay/node_modules/swig/index.js:109:26)
    at Object.compile (/home/vijay/node_modules/swig/index.js:153:16)

If I change JSON.parse( item ).title to JSON.parse( item ) above, instead of errors I get this in my view:

function parse() { [native code] }

Here's a look at the item JSON object:

item { 
    id     : 2,
    title  : 'City Life ',
    author : 'Timothy J. Lindenburg',
    date   : 1337498792626,
    indent : 0         
}

Simply put, I want to access the individual keys and values of item in Swig but I can't get JSON.parse() to work. Would appreciate it if someone would point me in the right direction (I'm told Swig is based on Django templates so if you've worked with those, this should be easy).


回答1:


I don't know why you want to parse it. In swig it already is JSON. So to get the title, change {{ JSON.parse(item).title }} to {{ item.title }} .



来源:https://stackoverflow.com/questions/10671620/json-parse-in-swig-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!