【问题标题】:Get list values in a Django Template在 Django 模板中获取列表值
【发布时间】:2010-12-02 11:49:25
【问题描述】:

在视图中:

return render_to_response('template.html',
                          {'headers': list(sort_headers.headers()) },
                          context_instance=RequestContext(request))

在模板中:

{{ headers }}
<br />
{{ headers|slice:"1" }}

在浏览器中:

[{'url': '?ot=desc&amp;o=0', 'text': 'Nombre', 'class_attr': ' class="sorted ascending"', 'sortable': True}, {'url': '?ot=asc&amp;o=1', 'text': 'Valor', 'class_attr': '', 'sortable': True}, {'url': '?ot=asc&amp;o=2', 'text': 'Inventario', 'class_attr': '', 'sortable': False}, {'url': '?ot=asc&amp;o=3', 'text': 'Fecha Creacion', 'class_attr': '', 'sortable': True}]

[{'url': '?ot=desc&amp;o=0', 'text': 'Nombre', 'class_attr': ' class="sorted ascending"', 'sortable': True}]

我得到一个带有{{ headers|slice:"1" }} 的列表节点,但是现在,如何获得一个字典值?例如“url”返回'?ot=desc&amp;amp;o=0'

注意:不能使用{% for %}

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    {{ headers.1.url }}

    来自http://docs.djangoproject.com/en/dev/topics/templates/#variables

    从技术上讲,当模板系统遇到点时,它会按以下顺序尝试以下查找:
        * 字典查找
        * 属性查找
        * 方法调用
        * 列表索引查找

    因此,您可以使用 {{ headers.1 }} 代替 {{ headers|slice:"1" }}。然后要访问 url 键,只需附加它:{{ headers.1.url }}。

    HTH。

    【讨论】:

      【解决方案2】:

      我想你想要:

      {% with headers|slice:"1" as data %}
      <a href="{{ data.url }}"{{ data.class_attr|safe }}>{{ data.text }}</a>
      {% endwith %}
      

      【讨论】:

        【解决方案3】:

        我不确定我是否理解您的问题,但要从模板中的字典中获取值,您可以使用方法项或值。

        如果你使用 {{dict.items}},你会得到一个元组列表(键,值),你可以简单地使用 tuple.1 来获取值。

        如果您使用 {{dict.values}},您只会得到字典值的列表。

        【讨论】:

          猜你喜欢
          • 2012-02-15
          • 2018-09-23
          • 2022-12-21
          • 1970-01-01
          • 2021-10-24
          • 2016-06-14
          • 2011-11-22
          • 2019-03-28
          相关资源
          最近更新 更多