How to access an attribute of an object using a variable in django template?

后端 未结 2 1289
逝去的感伤
逝去的感伤 2021-01-12 08:49

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_inscr         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 09:20

    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 %}
    

    You can read more about writing custom template tags.

提交回复
热议问题