In python it is possible to dynamically create variables names using eval('dyn_var_name')
.
I want to do this in my mako template but the example code below:
from mako.template import Template
print Template("hello ${eval('data{}'.format(0))}!").render(data0="world")
returns with a NameError: name 'data0' is not defined
, ie. the variable name is still a string 'data0'
and doesnt correspond to the appropriate keyname data0
; eval()
hasnt done its job. How to go about accomplishing this?
thx in advance
You could do this using the pageargs
dictionary rather than eval
:
from mako.template import Template
print Template("hello ${pageargs['data{}'.format(0)]}!").render(data0="world")
However, from your example it sounds like you might have a bunch of variables each named like data0
, data1
, data2
, etc. Why not pass them to render as a list rather than as many similarly named variables? Something like:
`Template("hello ${data[0]}!").render(data=["world"])`)
Also see keep data out of your variable names.