Search code examples
pythonjinja2template-enginemako

Which python template language allows filling in variables from a dictionary?


I want to generate a configuration file for some external software package. The configuration file requires some sensitive information like AWS access keys and passwords etc. I want to make these configuration files public on github but obviously I don't want to hardcode and expose these credentials.

The credentials also have to show up in the right place in the config file so I can't just "cat" them on to the end.

I figured that using a tempting language like jinja2,mako, django etc would be a good solution. Then I can just put the the templates online and require the user to make a new file with credentials and run a script (that I provide) to render the template. A template engine would also enable other more sophisticated editing (I think).

Can someone recommend a particular template engine that would make this easy? I imagine something where you make a template and then render it by providing a dictionary containing the variables to assign. Maybe they all do this. I don't know.

To be a little more specific I would like something that does something like this

Template("Hello {{name}}, you are #{{num}}").render({"name":"Joe","num":1}) 

All the templates that I see look like this

Template("Hello {{name}}, you are #{{num}}").render(name="Joe", num=1)

That makes it difficult to write a general program which reads a parameter file of key value pairs and hands them to a template to render. For example, it might require using "eval" which is awkward.


Solution

  • If your templating language only allows render(a=foo, b=bar), you can work around it like so: d = {"a": foo, "b": bar}; render(**d) -- no need for eval.

    For more info, read https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists