简体   繁体   中英

how to use eval() in python mako templating

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM