2

I am a newbie for mako and want to create .py scripts programatically from a template .py script. So does something like this work

Lets say my template script has a variable var1 = ${var1}, that takes say integer values. I want to be able to create many copies with particular values of var1 variable. How I create a caller that declares var1 as a list, say var1 = [1,2,3,4] and iterate over the values and pass them to the template. How does one do this, does something like render(**locals()) work?

Also I am unable to download Mako, is there a windows python 2.7 download available?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
ganesh reddy
  • 1,842
  • 7
  • 23
  • 38

1 Answers1

3

Once you have a template object, you can just iterate over the values you need and use the render method to obtain the new output as follows:

from mako.template import Template

template = Template('var1 = ${var1}')

for v in range(1, 5):
    context = {'var1': v}
    print template.render(**context)

Example output:

var1 = 1
var1 = 2
var1 = 3
var1 = 4

Regarding the idea of using locals(), that would certainly work:

for var1 in range(1, 5):
    print template.render(**locals())

Anyway, I prefer to explicitly create the context dictionary. This is consistent with the zen of python whith states that explicit is better than implicit.

Finally, with regard to the installation problem, I don't know of any binary available, but you can install using pip as explained in the mako download page.

jcollado
  • 39,419
  • 8
  • 102
  • 133
  • Thanks, can you please elaborate on what context and ** context does – ganesh reddy Mar 04 '12 at 15:33
  • Also what gets passed in when I say **locals, is it all the variables in the current local scope, so if I run this out of a script, all the vars defined in the script basically? Many thanks. – ganesh reddy Mar 04 '12 at 15:45
  • When you use `**context`, the dictionary pairs are expanded as if the method were called like `template.render(var1=v)`. For more information, please have a look at this [related question](http://stackoverflow.com/q/1769403/183066). – jcollado Mar 04 '12 at 17:36
  • When you use `locals` all the variables in the [local symbol table](http://docs.python.org/library/functions.html#locals) are passed. In the example above, is something like: `{'var1': 4, 'template': , '__builtins__': , '__file__': 'test.py', '__package__': None, 'Template': , '__name__': '__main__', '__doc__': None}`. Despite this works, I don't really like it because you're passing more variables than needed to the template. – jcollado Mar 04 '12 at 17:39