【问题标题】:Django display contents of list in a templateDjango在模板中显示列表内容
【发布时间】:2011-09-12 10:31:03
【问题描述】:

我对 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>

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

【问题讨论】:

    标签: python django list templates


    【解决方案1】:

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

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

    <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>
    

    【讨论】:

      【解决方案2】:

      如果您提及storeOfAuthorNames 的数据格式、您当前获得的输出以及您所期望的内容,将会有所帮助。

      从你的观点我只能说:

      • authors (storeOfAuthorNames) 由getAuthorName(soup) 制作
      • 如果checkIfValidClass(...) 返回False,当您尝试引用storeOfAuthorNames 时,您将得到一个NameError,因为它是未声明的

      如果我必须仅根据您的示例模板来猜测您的问题出在哪里,我会说您的问题出在authors|safe。您需要对要打印的值应用safe 过滤器,而不是列表本身。即

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-11
        • 2015-11-09
        • 2022-11-15
        • 2019-05-28
        • 1970-01-01
        • 2012-04-17
        • 2017-07-21
        • 2020-03-30
        相关资源
        最近更新 更多