I’ve tried to search for the answer to this around the web, and I’m not sure if I’m phrasing it properly or not, but I can’t seem to find my answer. What I’d like to do is write a function that does some work with arguments in which some are of known values (input/output files) but some are unknown in number (jinja value passing). I understand the idea of *args, but I don’t think that will work in this case.
Here’s what I’d like to work:
from jinja2 import Template def myTemplate(inputFile, outputFile *args): with open(inputFile, 'r') as r: render = Template(r.read()) outputFile = render.render(*args)
The last line of this could be one dictionary, two or three single variables, etc. I do this several times in a script (without a dedicated function), but it’s this last part that is keeping me from writing it as a single function and then just calling it. Feels like sloppy coding to not wrap a function around this because, other than this last line, the code is identical.
solution was simply using **kwargs correctly…
from jinja2 import Template def myTemplate(inputFile, outputFile **kwargs): with open(inputFile, 'r') as r: render = Template(r.read()) outputFile = render.render(**kwargs)
with this you can pass as many variables to the render engine of jinja as you’d like.
Answered By – acousticpanic
Answer Checked By – Pedro (BugsFixing Volunteer)