문제

This is simplified but it describes fundamentally what I'm trying to do.

In my views.py, I'm building a list of lists. Each list contains a store name, a list of (product, price) tuples, and a list of (employee, age) tuples. Both the tuple lists are of indeterminable length (but are the same length in each respective line). The outer list containing the name and tuple lists is also of indeterminable length.

[[store_name,         [(product_1a, price_1a),(product_2a,price_2a),...],  [(employee_1a, age_1a), (employee_2a, age_2a),...]]
 [another_store_name, [(product_1b, price_1b),(product_2b,price_2b),...],  [(employee_1b, age_1b), (employee_2b, age_2a),...]]
 ...                                                                                                                          ]

Each line of the above package needs to be unpacked into one row of a table in my template. I'm trying the following code for my template:

{% for name, products, employees in package %}
  <tr>
      <td>{{ name }}</td>
    {% for product, price in products %}
      <td>{{ product }}</td> <td>{{ price }}</td>
    {% endfor %}
    {% for employee, age in employees %}
      <td>{{ employee }}</td> <td>{{ age }}</td>
    {% endfor %}
  </tr>
{% endfor %}

Actually - I've tried about a dozen different solutions and am at my wits end. Any help on how to repackage and unpack successfully in a template to achieve the desired goal would be most appreciated!

P.S. I'm not really working with store_names, products and employees but this seems the simplest way to put it in a post. I understand totally if you question the need to have this sort of data in one table row!

도움이 되었습니까?

해결책

You can access array sequence elements in the template via arr.0, arr.1 etc. See documentation here: https://docs.djangoproject.com/en/1.4/topics/templates/#variables

So try something like this:

{% for item in package %}
  <tr>
      <td>{{ item.0 }}</td>
    {% for product in item.1 %}
      <td>{{ product.0 }}</td> <td>{{ product.1 }}</td>
    {% endfor %}
    {% for employee in item.2 %}
      <td>{{ employee.0 }}</td> <td>{{ employee.1 }}</td>
    {% endfor %}
  </tr>
{% endfor %}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top