简体   繁体   中英

In Django, how do I use a list item's String value to get an object's variable's value?

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM