Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping double quotes while rendering in Jinja2

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...

like image 722
Cris Motinha Avatar asked Jan 25 '17 13:01

Cris Motinha


People also ask

How do you escape jinja2?

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.

How do you escape a double quote?

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.

How do you escape a single quote in Jinja?

The right way to escape that is to use to backslashes (the backslash that escapes the single quote needs to be escaped too).

How do you escape a double quote in query string?

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.


2 Answers

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.

like image 166
Daniel Roseman Avatar answered Oct 13 '22 01:10

Daniel Roseman


The alternative way to do this would have been

e.({{ function|safe }})

which prevents auto-escaping.

like image 37
sberry Avatar answered Oct 13 '22 00:10

sberry