5

My jinja template gets an object which has many variable names, this attributes vary and so their names, I am looking for a way to access this attributes based on a prefix and a for loop:

{% for i in Object.vars %}
    <h1> {{ Object.attribute_ + i }} </h1>
{% endfor %}

I'm trying to access Object.attribute_1, Object.attribute_2 and so on. the code above of course won't work, but I can't think on a way of doing this.

PepperoniPizza
  • 8,842
  • 9
  • 58
  • 100

2 Answers2

6

Keep in mind that doing too much logic in your template files will cause (long term) issues to maintain your code.

I would say, keep your logic outside of the template and create a list of your objects before rendering the template, using the getattr() function:

for i in Object.vars:
    list_of_objects.append(getattr(Object, 'attribute_' + i))

Now when rendering the template pass the list to like that:

render_template('page.html', list_of_objects=list_of_objects)
Or Duan
  • 13,142
  • 6
  • 60
  • 65
1

The canonical way to solve problems like this is to pass a structure such as a list or dict. Dynamic variable names are almost always a terrible idea.

holdenweb
  • 33,305
  • 7
  • 57
  • 77