Nick Heiner
Nick Heiner

Reputation: 122412

Django: using variables as array indices?

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?

Upvotes: 0

Views: 605

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881567

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.

Upvotes: 2

Adam
Adam

Reputation: 7207

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/.

Upvotes: 1

Related Questions