Escaping double quotes while rendering in Jinja2

2019-04-07 18:29发布

问题:

I'm using Jinja2 to create Golang code using Python3. I need to pass some parameters in quotes to a function in my final code, but Jinja2 isn't escaping double quotes. My python code is something like:

list_s = ['a', 'b']
string = '\"' + '", "'.join(list_s) + '\"'
final_string = 'Function(' + string + ')'
print(final_string)

template.render({'function': final_string})

My template is:

e.({{function}})

What I'm getting in the console (the print in the python code):

Function("a", "b")

What I wanted in my final code in Go:

e.(Function("a", "b"))

What I'm actually getting in my final code:

e.(Function("a", "b"))

I've already tried:

'`\"`' , '`"`', "'\"'", "\\\"", "\N{Quotation Mark}"

And none of them worked as I wanted. Any ideas?

Thank you :))

"Solved":

I changed from double quotes to `, so my python code now is:

string = '`' + '`, `'.join(list_s) + '`'

And my final Go code is:

e.(Function(`a`, `b`))

And this works on Go. It isn't the best solution but it is working...

回答1:

The alternative way to do this would have been

e.({{ function|safe }})

which prevents auto-escaping.



回答2:

This is due to Jinja2 autoescaping. As described in the documentation, the recommended way to avoid this is to wrap the text in a Markup object.