I am trying to pass a dictionary to a django template. In the django view, the variable is initialized and passed as such:
我正在尝试将字典传递给django模板。在django视图中,变量被初始化并按原样传递:
foo = {'a':'b'}
...
return render(request, 'template.html', {'foo': str(foo)}
In the template, I have
在模板中,我有
{{ foo|default:"{}"|safe}}
In case it's relevant, I have the above line in a jquery snippet. That snippet is failing because the dict is being rendered as
如果它是相关的,我在jquery片段中有上面的行。该片段失败,因为dict被渲染为
[{'a': u'b'}]
instead of what I expect:
而不是我期望的:
[{'a': 'b'}]
It seems the safe filter is not removing the unicode u preceding the dict value 'b'. How do I do that?
似乎安全过滤器没有删除dict值'b'之前的unicode u。我怎么做?
5
You should be using a function to explicitly convert it to JSON, because of a few subtle differences between JSON and the default Python stringification:
您应该使用函数将其显式转换为JSON,因为JSON和默认Python字符串化之间存在一些细微差别:
A string in JSON technically must be delimited with "
rather than '
, though parsers tend to accept the latter too (see the string rule on json.org)
在技术上,JSON中的字符串必须用“而不是”分隔,尽管解析器也倾向于接受后者(请参阅json.org上的字符串规则)
Bool literals are lowercase
Bool文字是小写的
If your data contains things other than numbers, strings, lists and dicts, using str
on them will probably silently produce invalid JSON
如果您的数据包含数字,字符串,列表和dicts以外的内容,那么使用str可能会无声地生成无效的JSON
Use a template filter such as django-jsonify:
使用模板过滤器,如django-jsonify:
{% load jsonify %}
...
{{ foo|jsonify }}
0
The reason I was experiencing this problem was because my dictionary actually included a unicode value. The toy example above was a simplification. when i ran str(val)
before inserting val into the dict, the rendering occurred as expected.
我遇到这个问题的原因是因为我的字典实际上包含了一个unicode值。上面的玩具示例是简化。当我在将val插入dict之前运行str(val)时,渲染按预期发生。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.silva-art.net/blog/2013/03/22/fc1fdbc2e47e7f37f1814c4fc3f6c228.html。