【问题标题】:Showing data in Bootstrap list-group in Django template在 Django 模板的 Bootstrap 列表组中显示数据
【发布时间】:2016-10-14 17:52:16
【问题描述】:

我有汽车数据,我希望它们显示在 Bootstraps 列表组中。问题是我希望一个汽车品牌只显示一次。

{u'cars': [{u'brand': u'Ford', u'model': u'Focus'}, {u'brand': u'u'Ford', u'model': u'Fiesta'}, {u'brand': u'u'Toyota', u'model': u'Hilux'}]

我在views.py中附加到列表汽车:

for i in readable_json["cars"]:
            cars.append({
                'brand': i['brand'],
                'model': i['model'],
               })

所以,在本例中,我希望在 Bootstrap 列表组中显示如下:http://www.bootply.com/XEnAquIInD

不喜欢这样: http://www.bootply.com/2YX7PgB1ch

问题出现在 Django 模板中。当我在模板中循环汽车时,我需要在 HTML 中为列表项设置不同的数据父 ID。另外,我如何才能检查显示的汽车品牌不超过一次?

<div id="MainMenu">
        <div class="list-group panel">
          <div href="#demo" class="list-group-item list-group-item-success"  data-parent="#MainMenu">Laitteet</div>
          <div class="collapse in" id="demo">

          {% for car in cars %}

          <a href="#{{ ??? }}" class="list-group-item" data-toggle="collapse" data-parent="#{{ ??? }}">{{ car.brand }} <i class="fa fa-caret-down"></i></a>

            <div class="collapse list-group-submenu" id="{{ ??? }}">
              <a href="#" class="list-group-item" data-parent="#{{ ??? }}">{{ car.model }}</a>
            </div>
        {% endfor %}
      </div>
  </div>
</div>

【问题讨论】:

  • 您不应该执行诸如检查模板中的唯一性之类的逻辑-您需要在视图中执行此操作并在将数据传递给模板之前对其进行过滤。然后添加唯一 ID 变得简单。
  • 我应该做两个列表吗?一个用于汽车,一个用于 ID:s?
  • 没有。这部分取决于您的数据来自哪里——它在源头是否有唯一的 ID(例如,数据库 ID?)。如果没有,您可以slugify 一个独特的字段,例如汽车名称。
  • 这看起来不错。我仍然无法弄清楚我应该如何以可以在列表中正确获取数据的形式将数据从视图获取到模板。

标签: python django twitter-bootstrap django-templates


【解决方案1】:

我会做这样的事情来清理你视图中的数据:

cars_seen = set()
for i in readable_json["cars"]:
    car_identifier = '{}-{}'.format(i['brand'], i['model'])
    if not car_identifier in cars_seen:
        cars.append({
            'brand': i['brand'],
            'model': i['model'],
            'id': car_identifier,
        })
    cars_seen.add(car_identifier)

cars 现在将包含一个独特汽车列表(假设 brand + model 是您定义独特性的方式)。

然后,您可以在模板中生成具有以下内容的唯一 ID:

<a href="#{{ car.car_identifier|slugify }}">...</a>

【讨论】:

  • 汽车列表仍然可能有多次相同的品牌名称,如下所示:bootply.com/2YX7PgB1ch,因此标识符无法正常工作。
  • 是的 - 如果您按照我的代码进行操作,就可以解决这个问题。您不会在这里获得现成的解决方案,需要了解底层逻辑以便您自己实现它。
猜你喜欢
  • 2021-11-02
  • 2011-07-10
  • 1970-01-01
  • 2012-03-18
  • 2019-05-28
  • 1970-01-01
  • 2021-06-13
  • 2014-11-12
  • 2014-01-13
相关资源
最近更新 更多