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...
To escape jinja2 syntax in a jinja2 template with Python Flask, we can put render the template code without interpretation by putting the code in the {% raw %} block.
If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.
The right way to escape that is to use to backslashes (the backslash that escapes the single quote needs to be escaped too).
Double Quotes inside verbatim strings can be escaped by using 2 sequential double quotes "" to represent one double quote " in the resulting string. var str = @"""I don't think so,"" he said.
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.
The alternative way to do this would have been
e.({{ function|safe }})
which prevents auto-escaping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With