当传递给 HTML 模板时,JSON 响应不是一个真实的字符串?
我对以下行为感到困惑:
使用 Freebase-Python,我向 Freebase API 发送一个请求,该请求是对 JSON 响应的查询。例如,我得到响应:
"status": "200 OK",
"code": "\/api\/status\/ok",
"result": {
"\/common\/topic\/weblink": [
{
"url": "http:\/\/www.boardgamegeek.com\/boardgame\/13\/Settlers of Catan",
"description": "BoardGameGeek"
}
],
"id": "\/en\/settlers_of_catan"
}
在我用来发出请求的同一个 RequestHandler 类中,我可以执行以下操作:
print result.id
>>> /en/settlers_of_catan
print result["/common/topic/weblink"][0].url
>>> http://www.boardgamegeek.com/boardgame/13/Settlers of Catan
但是,当我将结果对象传递给 HTML 模板时,奇怪的行为开始了。
我可以这样做,
{{ result.id }}
这将在浏览器中呈现“/en/settlers_of_catan”。但是如果我尝试,
{{ result["/common/topic/weblink"][0].url }}
我收到错误:
raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:]
TemplateSyntaxError: Could not parse the remainder: ["/common/topic/weblink"][0].url
我也可以只显示结果:
{{ result }}
浏览器中的结果:
{u'/common/topic/weblink': [{u'url': u'http://www.boardgamegeek.com/boardgame/13/Settlers of Catan', u'description': u'BoardGameGeek'}], u'id': u'/en/settlers_of_catan'}
我的问题是,为什么可以我是否可以像从 RequestHandler 中一样访问 HTML 模板中的结果?
I'm confused by the following behavior:
Using Freebase-Python, I send a request to the Freebase API that is a query for a JSON response. I get the response, for example:
"status": "200 OK",
"code": "\/api\/status\/ok",
"result": {
"\/common\/topic\/weblink": [
{
"url": "http:\/\/www.boardgamegeek.com\/boardgame\/13\/Settlers of Catan",
"description": "BoardGameGeek"
}
],
"id": "\/en\/settlers_of_catan"
}
Within the same RequestHandler class that I used issue the request, I can do things like,
print result.id
>>> /en/settlers_of_catan
print result["/common/topic/weblink"][0].url
>>> http://www.boardgamegeek.com/boardgame/13/Settlers of Catan
However, when I pass the result object to an HTML template, the weird behavior starts.
I can do,
{{ result.id }}
Which will render "/en/settlers_of_catan" in the browser. But if I try,
{{ result["/common/topic/weblink"][0].url }}
I get an error:
raise TemplateSyntaxError, "Could not parse the remainder: %s" % token[upto:]
TemplateSyntaxError: Could not parse the remainder: ["/common/topic/weblink"][0].url
I can also just display the result:
{{ result }}
Which results in the browser:
{u'/common/topic/weblink': [{u'url': u'http://www.boardgamegeek.com/boardgame/13/Settlers of Catan', u'description': u'BoardGameGeek'}], u'id': u'/en/settlers_of_catan'}
My question is, why can't I access the result in the HTML template the same way I can from the RequestHandler?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 django 模板语言字典中,列表索引和属性查找是使用点('.')组成。
因此,它应该类似于
{{ result.mylink.0.url }}
,但这很可能无法在键中使用斜杠!In the django template language dictionary-, list index and attribute lookups are made using a dot ('.').
For that reason it should be something like
{{ result.mylink.0.url }}
, but this will most like not work using slashes in the key!