On 26 août, 04:00, Yo-Yo Ma <baxterstock...@gmail.com> wrote:
> I'm wanting to build out a list template that can display any list of
> objects in this manor (pseudo code:
>
> {% for thing in things %}
> <tr>
>     <td>{{ thing.foo }}</td>
>     <td>{{ thing.bar }}</td>
>     <td>{{ thing.spam }}</td>
>     <td>{{ thing.eggs }}</td>
> </tr>
> {% endfor %}
>
> The problem is, of course, that I want to list more than just "things"
> using the same template. Things have "foo", "bar", "spam", and "eggs".
> "Widgets" might only have "snafu", and "peanut_butter" attributes.
Well, the problem is not really with the template code - mostly
trivial FWIW, but mostly : how do you decide which attributes you want
to display for a given object ? Once you have this sorted, you can
preprocess the objects list in the view code as Steve suggested:

# views.py
def view(request, ...):
   objects = however_you_get_your_objects()
   attributes = however_you_get_the_attribute_names()
   data = []
   for obj in objects:
       data.append(tuple(getattr(obj, attr) for attr in attributes))
   context = {
      attributes=attributes,
      data=data
    }
   return render_to_response("template.html", context)

# template.html
<table>
  <tr>
  {% for name in attributes %}
    <th>{{ name }}</th>
  </tr>
  {% endfor %}
  {% for row in data %}
  <tr>
     {% for field in row %}
      <td>{{ field }}</td>
     {% endfor %}
  </tr>
  {% endfor %}
</table>

This of course imply that your objects list is homomgenous...


-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-us...@googlegroups.com.
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en.

Reply via email to