在模板中将json渲染为字典

0 投票
2 回答
1449 浏览
提问于 2025-04-16 07:38

我从服务器得到了一个JSON对象,长得像这样:

{"1":{"id":"1","name":"autos"},
"2":{"id":"2","name":"business"},
"3":{"id":"3","name":"cities"},
"4":{"id":"4","name":"drama"},
"5":{"id":"5","name":"movies"},
"6":{"id":"6","name":"finance"},
"7":{"id":"7","name":"electronics"}}

接着,我用这个JSON生成了一个字符串模板:

<h3>Ugly, raw list. Yuck !</h3>
1: {{ interests }}
<ul>
    {% for k,v in interests.items %}
        <li>{{k}}. - {{ v }}</li>
    {% endfor %}
</ul>

template_name = 'socialauth/interests.html'
html = render_to_string(template_name, RequestContext(request, {'interests': ResultDict,}))

结果是这样的:

<h3>Ugly, raw list. Yuck !</h3>
1: {&quot;1&quot;:{&quot;id&quot;:&quot;1&quot;,&quot;name&quot;:&quot;autos&quot;},&quot;2&quot;:{&quot;id&quot;:&quot;2&quot;,&quot;name&quot;:&quot;business&quot;},&quot;3&quot;:{&quot;id&quot;:&quot;3&quot;,&quot;name&quot;:&quot;cities&quot;},&quot;4&quot;:{&quot;id&quot;:&quot;4&quot;,&quot;name&quot;:&quot;drama&quot;},&quot;5&quot;:{&quot;id&quot;:&quot;5&quot;,&quot;name&quot;:&quot;movies&quot;},&quot;6&quot;:{&quot;id&quot;:&quot;6&quot;,&quot;name&quot;:&quot;finance&quot;},&quot;7&quot;:{&quot;id&quot;:&quot;7&quot;,&quot;name&quot;:&quot;electronics&quot;}}
<ul>   
</ul>

看起来我的 {{ interests }} 变量没有被当作字典来处理。为什么会这样呢?更糟的是,现在我把这个生成的列表放到一个父模板里,而这个父模板也是以字符串的形式生成的(因为我是用ajax加载的)。最后的结果是这样的:

模板:

<div class="connect-twitter" style="background:#f8f8f8">
    <div id="likes-list">
        {{ likes|safe }}
    </div>
    <a href="#" class="submit-step-2">Proceed</a>  
</div>

结果:

Content-Type: text/html; charset=utf-8
{"html": "<h3>Ugly, raw list. Yuck !</h3>\n\n1: {&quot;1&quot;:{&quot;id&quot;:&quot;1&quot;,&quot;name&quot;:&quot;autos&quot;},&quot;2&quot;:{&quot;id&quot;:&quot;2&quot;,&quot;name&quot;:&quot;business&quot;},&quot;3&quot;:{&quot;id&quot;:&quot;3&quot;,&quot;name&quot;:&quot;cities&quot;},&quot;4&quot;:{&quot;id&quot;:&quot;4&quot;,&quot;name&quot;:&quot;drama&quot;},&quot;5&quot;:{&quot;id&quot;:&quot;5&quot;,&quot;name&quot;:&quot;movies&quot;},&quot;6&quot;:{&quot;id&quot;:&quot;6&quot;,&quot;name&quot;:&quot;finance&quot;},&quot;7&quot;:{&quot;id&quot;:&quot;7&quot;,&quot;name&quot;:&quot;electronics&quot;}}\n\n<ul>\n    \n</ul>"}

当这段代码插入到HTML中时,看起来真是糟糕:

http://img204.imageshack.us/img204/3858/listaxv.png

这是怎么回事?为什么它没有正常渲染成字符串,而是加了一些'内容类型'的头信息?

2 个回答

0

你有没有对响应做什么转换,比如用 $parseJSON(string) 或 eval(string) 把响应转换成一个 JavaScript 对象?

0

看起来模板变量 interests 只是一个包含 JSON 响应的字符串。这个字符串在模板中被转义了,所以你看到的都是一些引号。你需要检查一下服务器的响应是否被正确解析。

要确认数据的类型,你可以使用类型类,比如 type(ResultDict)

撰写回答