gpt4 book ai didi

python - Django 在模板中显示列表的内容

转载 作者:行者123 更新时间:2023-11-28 22:04:20 25 4
gpt4 key购买 nike

我对 Django 的模板系统还很陌生——基本上,我试图打印出我在上下文中传递给 django 的列表的所有内容。

我的 urls.py 的相关部分在这里-

 url(r'^class/$', twobooks.classes.views.getAllInformation, {'template_name':'classes/displayBooks.html'}),

现在,在我看来getAllInformation 如下-

def getAllInformation(searchTerm,template_name):
nameAndNumberStore = modifySearchTerm(searchTerm)
url = modifyUrl(nameAndNumberStore)
soup = getHtml(url)
information = []
if (checkIfValidClass(soup,nameAndNumberStore)):
storeOfEditions = getEdition(soup)
storeOfAuthorNames = getAuthorName(soup)
storeOfBookNames = getBookNames(soup)
storeOfImages = getImages(soup)
information.append(storeOfAuthorNames)#REMEMBER this is a list of two lists
information.append(storeOfEditions)
return render_to_response(
template_name,
{'authors': storeOfAuthorNames},
)

而displayBooks.html如下-

<html>
<head>
<body>
<h1>Testing the class page backend</h1>
<ul>
{ % for author in authors|safe% }
<li>{{ author }}</li>
{ % endfor % }
</ul>

</body>

</html>

我认为这很简单,但我不确定发生了什么,所以我想寻求帮助 - 谢谢!

最佳答案

应用safe过滤器会将任何内容 转换为字符串。如果您从文字 [1, 2, 'foo', u'bar'] 开始,您将以大致文字 u"[1, 2, ' foo', u'bar']"(或类似的东西——我不太确定它是如何呈现的,因为我从未尝试过这样做;我也说“大约”,因为它实际上是一个 SafeString 实例不是 unicode 实例)。然后,迭代遍历生成的字符串中的每个字符,这不是您想要的。

相反,您可以使用 safeseqsafe 过滤器应用于序列中的每个元素的过滤器,

<ul>
{% for author in authors|safeseq %}
<li>{{ author }}</li>
{% endfor %}
</ul>

或者,您可以将 safe 应用于迭代器内的值。

<ul>
{% for author in authors %}
<li>{{ author|safe }}</li>
{% endfor %}
</ul>

我会推荐 safeseq,因为如果您愿意,您可以进一步优化模板,使用 unordered_list过滤器,如果您只想显示值。 (请注意,我不确定它的行为方式——这可能会将其取消标记为安全。您需要尝试一下。)

<ul>{{ authors|safeseq|unordered_list }}</ul>

关于python - Django 在模板中显示列表的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7386512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com