[英]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. 假定列是包含字符串的列表,每个字符串表示对象o的变量之一。
<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 . 我对django不太熟悉,无法知道是否有内置的功能,但是...您可以将自己的
getattr
版本定义为模板过滤器 。 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: 要使用它,您将像使用其他两个arg模板过滤器一样使用它:
{{ o|my_getattr:col }}
Here's a full example (don't forget the "load" directive at the top!): 这是一个完整的示例(不要忘记顶部的“ load”指令!):
{% 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! 如果您以前从未制作过自定义模板过滤器,请务必阅读文档!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.