Search code examples
pythonmako

Create a simple python object and send it back to Mako.template.render()


I am using Mako to create some configuration templates for network routers.

I would like to create a simple router Object i.e

File routers.py

class myRouter(Object):

     def name(self):
          return "Foo"

     def interfaces(self):
          return [{'name':'loopback','address':'127.0.0.1'},{...}]

and then render it using Mako and my template

Exec:

from mako import *
from routers import myRouter
z = myRouter()
mytemplate = Template(filename='config.mako')
print mytemplate.render(router=z)

File config.mako

Router name is ${router.name()}!
Router interfaces are :
% for i in router.interfaces():
     ${i.name} -> ${i.address}
% endfor

Output:

Router name is

<bound method Router.name of <pyrouteur.Router object
> at 0x7fa10a912310>>

How can I avoid this behavior?

Thks!


Solution

  • You need to create an instance of the class myRouter and then pass that to the render method, currently you are passing the class itself as the argument.

    Your code should look something like this:

    r = myRouter()
    t.render(router =r)