PepperoniPizza PepperoniPizza - 1 year ago 322
Python Question

Jinja2 dynamic variable building

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.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download