Search code examples
pythontemplatesmako

Passing lots of values to template


How do i pass a lot of values to my template?

Documentation taken straight from the Mako Website:

myPythonProgram.py:

from mako.template import Template

mytemplate = Template(filename='myHtmlTemplate.htm')
print mytemplate.render(name="jack") #<- how to pass like 40 more variables?

myHtmlTemplate.htm

<html>
<head>
</head>
<body>
<p> ${name} </p>
</body>
</html>

This solution works fine for like under 10 but i want to use up to 40 Variables.

Thank you!


Solution

  • render() accepts an arbitrary number of positional arguments, and an arbitrary number of keyword arguments.

    From the information you've given, you should probably keep a dictionary of your 40 items.

    mydict = {'name': 'jack', 'age': 42, ... }
    

    A call to mytemplate.render(**mydict) will unpack the arguments, and then you can refer to ${name}, ${age} and so on in the template.