代码之家  ›  专栏  ›  技术社区  ›  Pankaj Sharma

django-在templatetag中显示OrderedDict

  •  1
  • Pankaj Sharma  · 技术社区  · 8 年前

    我有一个OrderedDict,我需要显示它的键,值,但我无法获得它的值,我有这个dict=([('sainbath','thesailor'),('HELLO','WORLD')),我已经尝试过这个

    {{object.specifications}}
          <ul>
            <li>{% for key in object.specifications %}
              {{key}}
              {%endfor%}
    

    我正在获取此输出

    OrderedDict([('sainbath','thesailor'),('HELLO','WORLD')]))

    • sainbath你好

    当我尝试这一点时,我只得到了它的键而不是值

    {{object.specifications}}
          <ul>
            <li>{% for key,value in object.specifications %}
              {{key}} : {{value}}
              {%endfor%}
    

    这给了我错误

    需要2个值才能在for循环中解包;得了8分。 请告诉我如何获得价值?

    1 回复  |  直到 8 年前
        1
  •  3
  •   py-D    8 年前

    1) 在模板中使用以下内容:

    {% for key,value in object.specifications.items %}
          {{key}}:{{value}}
    {% endfor %}
    

    2) 如果要将数据作为OrderedDict呈现模板,则可以使用以下方法进行相同的呈现。

    return render_to_response('your_template.html',{'data': sorted(your_ordered_dict.iteritems())})
    

    在模板中,您可以使用以下相同内容:

    {% for key, value in data %}
         {{key}}:{{value}}
    {% endfor %}
    

    希望它能帮助你!!

    推荐文章