views:

94

answers:

2

I am trying to create a template that will put items in a table.

Controller:

items = Item.all().order('name').fetch(10)

    template_values = {'items': items,
                       'headers': ['Name', 'Price', 'Quantity']}
    render('Views/table.html', self, template_values)

Template:

<table>
    <tr>
    {% for header in headers %}
        <th>{{header}}</th>
    {% endfor %}
    </tr>
    {% for item in items %}
        <tr><td><a href="detail/{{item.CSIN}}">{{item.name}}</a></td><td>{{item.CSIN}}</td></tr>
    {% endfor %}
</table>

Right now, the template is hard coded to look for certain attributes of item. I want to change this so it either looks for the attributes with the names that are in headers, or so that it looks for the first n attributes, where n is the length of headers.

How can I do this?

+1  A: 

I'm not sure if there is an existing template tag/filter that will accomplish what you want. You could look into writing a custom template tag or filter which accepts the items list and the current header and returns the value after the look-up. Have a look at http://docs.djangoproject.com/en/dev/howto/custom-template-tags/.

Adam
+2  A: 

You could tweak the view to do:

items = Item.all().order('name').fetch(10)
headers = ['Name', 'Price', 'Quantity']
viewitems = [[getattr(x, h) for h in headers] for x in items]

template_values = {'items': viewitems,
                   'headers': headers}
render('Views/table.html', self, template_values)

so all the template has to do is loop over each "item" (which will just be a list of the values to show corresponding to the headers. Basically, this would move the logic (deciding what to show) from the template (or actually split a bit each in template and view) entirely to the Python code in the view, simplifying the template and making it more general, as you desire.

Alex Martelli
You could make the viewitems lazily evaluated, since they are perhaps db queries?
Lakshman Prasad
Yes, I'm pretty sure you could -- use a genexp (round parentheses) rather than a listcomp (square brackets) for the outer level of `viewitems`. But with the `fetch(10` (that was already in the OP's question) the time savings should be modest (if present at all: 10 DB queries vs a single 10-items query...).
Alex Martelli