2

This is assuming that columns is a list containing Strings, each String is representing one of the object o's variable.

<tbody>
    {% for o in objects %}
    <tr>
        {% for col in columns %}
        <td>{{ o.col }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</tbody>

Example:

class Dog(models.Model):
    name = models.CharField()
    age = models.IntegerField()
    is_dead = models.BooleanField()

columns = ('name', 'age')

I cannot explicitly enter the object's variable name and must pass it as another list because I am trying to make a 'generic' template. Also, not all variables must be shown to the users.

1
  • have you tried replacing strings with (no argument) lambda-expressions in your view? Commented Jan 7, 2012 at 10:12

1 Answer 1

1

I'm not familiar enough with django to know if there's something builtin for this, but... you could just define your own version of getattr as a template filter. For some reason (I'm assuming because it's a builtin function), I wasn't able to simply register the builtin as a new template filter. Either way, this is how I've defined my version:

# This is defined in myapp/templatetags/dog_extras.py
from django import template

register = template.Library()

@register.filter
def my_getattr(obj, var):
    return getattr(obj, var)

To use it, you'll use it just like any other two arg template-filter:

{{ o|my_getattr:col }}

Here's a full example (don't forget the "load" directive at the top!):

{% load dog_extras %}

<table>
    <tbody>
        {% for o in objects %}
        <tr>
            {% for col in columns %}
            <td>{{ o|my_getattr:col }}</td>
            {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>

If you've never made custom template-filters before, be sure to read the docs!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.