如何使用Django模板中的变量访问对象的属性? [英] How to access an attribute of an object using a variable in django template?

查看:154
本文介绍了如何使用Django模板中的变量访问对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用变量访问对象的属性?我有这样的东西:

How can I access an attribute of an object using a variable? I have something like this:

{% for inscrito in inscritos %}
   {% for field in list_fields_inscrito %}
      {{inscrito.field}} //here is the problem
   {% endfor %}
{% endfor %}

例如Inscrito有:inscrito.id,inscrito.Name和inscrito.Adress,而我只想打印inscrito.id和inscrito.Name,因为id和Name在list_fields_inscrito。

For example Inscrito have: inscrito.id, inscrito.Name and inscrito.Adress and I only want to print inscrito.id and inscrito.Name because id and Name are in the list_fields_inscrito.

有人知道怎么做吗?

推荐答案

您可以为此编写模板过滤器:

You can write a template filter for that:

myapp / templatetags / myapp_tags.py

from django import template

register = template.Library()

@register.filter
def get_obj_attr(obj, attr):
    return getattr(obj, attr)

然后在模板中可以使用像这样:

Then in template you can use it like this:

{% load myapp_tags %}

{% for inscrito in inscritos %}
   {% for field in list_fields_inscrito %}
      {{ inscrito|get_obj_attr:field }}
   {% endfor %}
{% endfor %}

您可以阅读有关编写自定义模板标签

这篇关于如何使用Django模板中的变量访问对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆