Escaping double quotes while rendering in Jinja2

强颜欢笑 提交于 2019-12-12 07:49:38

问题


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.



来源:https://stackoverflow.com/questions/41852574/escaping-double-quotes-while-rendering-in-jinja2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!