【问题标题】:iterate through a dictionary in django template遍历 django 模板中的字典
【发布时间】:2018-05-24 09:06:45
【问题描述】:
{'provide a full refund of any money paid ': ['the ', 'dith ', 'with ', 'ande ', 'cor '], 'copyright laws of the place where you ar': ['e ', 'init ', ' or ', 'ate ', 's '], 'person or entity that provided you with ': ['the ', 'of ', 'ande ', ' or ', 'project '], 'michael s. hart is the originator of the': [' the ', '\n ', 's ', 'r ', ', ']}

我如何解析这个通过我的视图传递给 html 文件的 django 变量。 我想让这些数据以表格的形式显示在 html 文件中,其中显示每个键值

return render(request, 'notebook/instant_search.html', output)

我在我的 html 文件中尝试了这个,其中输出的是我正在通过我的视图传递的变量

{% for key, value in output %}
   {{ key }} <br>
    {% for key2 in value %}
       {{ key2 }} <br>
    {% endfor %}
{% endfor %} 

还有这个:

{% for k in context %}
    {{  k }}
{% endfor %}

但我没有得到任何输出。屏幕上什么都没有显示

【问题讨论】:

  • 请向我们提供您迄今为止尝试过的代码示例。这样我们就可以更有效地帮助您。
  • 完成。立即查看

标签: python html django-templates


【解决方案1】:

首先,您的 render 函数不接受正确的参数,这就是为什么您的 html 模板上没有任何内容。你输入了这个:

return render(request, 'notebook/instant_search.html', output)

正确的:

return render(request, 'notebook/instant_search.html', 'output':output)

以上将解决模板不显示来自渲染函数的数据的问题。

接下来是遍历字典的代码:

下面会显示列表中的每一项

{% for k, v in output.items %}
    {% for i in v %}
        {{ i }}
    {% endfor %}
{% endfor %}

而下面的代码将显示每个列表

{% for k, v in output.items %}
    {{ v }}
{% endfor %}

参考资料: https://docs.djangoproject.com/en/2.0/intro/tutorial03/

https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#render

【讨论】:

    【解决方案2】:
    return render(request, 'notebook/instant_search.html', {"output":output})
    

    在视图文件中更改此语句,然后您将获得输出

    <table>
    {% for key, value in output.items %}
    <tr>
    <td>{{key}}</td>
    <td>{{value}}<td> <!-- you can also run for on values list -->
    </tr>
    {% endfor %}
    </table>
    

    【讨论】:

      【解决方案3】:

      您可以直接在模板中迭代字典:

      <table>
      {% for key, value in my_dict.items %}
          <tr>
              <td>{{key}}</td>
              <td>{{value}}<td> <!-- you can also run for on values list -->
          </tr>
      {% endfor %}
      </table>
      

      希望对你有帮助

      【讨论】:

      • 好的,很抱歉,写答案时没有更新问题。如果您在输出上运行循环,它将不起作用,因为输出是上下文对象。您应该将输出添加到上下文本身以在输出上运行循环(在views.py中) return render(request, 'notebook/instant_search.html', {"output":output})
      猜你喜欢
      • 2019-07-14
      • 2011-12-22
      • 2019-10-22
      • 2016-08-31
      • 1970-01-01
      • 2021-12-20
      • 2011-10-11
      • 2020-08-03
      • 1970-01-01
      相关资源
      最近更新 更多