Question

I have several lists in this format mylist1,mylist2,mylist3,mylist4,....

I am trying to iterate through them in Python Bottle but I cannot find the right way

%for i in range(1,21):
{{mylist{{i}}[0]}} or {{mylist~i~[0]}} or {{mylist}}{{i}}[0] or {{mylist+i+[0]}} or {{mylist+i}}[0]
%end

But nothing from the above work.

Was it helpful?

Solution

You can get the variable value by name from the locals():

{{locals()['mylist' + str(i)][0]}}

Demo:

>>> from bottle import template
>>> template('{{locals()["list" + str(i)]}}', i=1, list1=[1,2,3,4])
u'[1, 2, 3, 4]'

Personally, I don't like the solution. Better construct a context dict with mylist1, mylist2 ... mylistn as keys and actual lists as values and pass it to the template:

>>> template('{{context["list" + str(i)]}}', i=1, context={'list1': [1,2,3,4]})
u'[1, 2, 3, 4]'

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top