在Jinja2中渲染时转义双引号 [英] Escaping double quotes while rendering in Jinja2
问题描述
我正在使用Jinja2通过Python3创建Golang代码。我需要在最终代码中将引号中的一些参数传递给函数,但是Jinja2不能转义双引号。
我的python代码类似于:
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})
我的模板是:
e.({{function}})
我在控制台中得到的内容(python代码中的打印内容):
What I'm getting in the console (the print in the python code):
Function("a", "b")
我在最终代码中想要的在Go中:
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"))
我已经尝试过:
'`\"`' , '`"`', "'\"'", "\\\"", "\N{Quotation Mark}"
它们都不如我所愿。有任何想法吗?
And none of them worked as I wanted. Any ideas?
谢谢:))
已解决:
我从双引号更改为`,所以我的python代码现在是:
I changed from double quotes to `, so my python code now is:
string = '`' + '`, `'.join(list_s) + '`'
最后我的Go代码是:
e.(Function(`a`, `b`))
这在Go上有效。
And this works on Go. It isn't the best solution but it is working...
推荐答案
这样做的替代方法应该是
The alternative way to do this would have been
e.({{ function|safe }})
可防止自动转义。
这篇关于在Jinja2中渲染时转义双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!