在Jinja2中渲染时如何转义双引号?

huangapple go评论103阅读模式
英文:

Escaping double quotes while rendering in Jinja2

问题

我正在使用Jinja2在Python3中创建Golang代码。我需要将一些参数以引号的形式传递给我的最终代码中的一个函数,但是Jinja2不会转义双引号。
我的Python代码大致如下:

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

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

我的模板是:

e.({{function}})

在控制台中(Python代码中的打印输出)我得到的结果是:

Function("a", "b")

我希望在我的最终Go代码中得到的结果是:

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

但实际上在我的最终代码中得到的结果是:

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

我已经尝试过以下方法:

'`' , '`', '\"\'\"\'', "\\\""

但它们都没有按照我期望的方式工作。有什么想法吗?

谢谢 :))

"解决方案":

我将双引号改为反引号,所以我的Python代码现在是:

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

我的最终Go代码是:

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

这在Go中可以正常工作。虽然这不是最好的解决方案,但它能正常工作...

英文:

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

得分: 25

这样做的另一种方式是

e.({{ function|safe }})

这样可以防止自动转义。

英文:

The alternative way to do this would have been

e.({{ function|safe }})

which prevents auto-escaping.

答案2

得分: 1

这是由于Jinja2的自动转义功能。如文档中所述,避免这种情况的推荐方法是将文本包装在一个Markup对象中。

英文:

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.

huangapple
  • 本文由 发表于 2017年1月25日 21:14:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/41852574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定