Jinja2 dynamic variable building

My jinja template gets an object that has many variable names, these attributes change and therefore their names, I am looking for a way to access these attributes based on the prefix and for loop:

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

      

I am trying to access Object.attribute_1, Object.attribute_2, etc. the code above will certainly not work, but I can't think of it.

+3


source to share


2 answers


Be aware that too much logic in template files will cause (long-term) problems 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 the rendered template is passed to the list like this:

render_template('page.html', list_of_objects=list_of_objects)

      

+4


source


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



+1


source







All Articles