1

I want to convert this code to something more inheritable to avoid coding. Consider that my code is simple and simple answer is need.

{{ entity.name }}
{{ entity.description }}

I want to convert to such code:

{% for attribute in attributes %}
{{ entity ??? }} == entity.get_attr(attribute)
{% end for %}

What is valid syntax for it?

2

1 Answer 1

2

The easiest example with filter:

# templatetags.ry
from django import template


register = template.Library()

@register.filter
def get_attr(object, name):
    return getattr(object, name, '')

Your template:

{% load templatetags %}


{% for attribute in attributes %}
    {{ entity|get_attr:attribute }}
{% end for %}
Sign up to request clarification or add additional context in comments.

2 Comments

Is not possible to do entity[name]?
It's possible if you use jinja2. But in jinga1 you have to use custom filter.

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.