Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django. Jquery. escaping string with quotes error

In a small forum, any user can save posts. Sometimes those posts include words surrounded by quotes ( " " ). This gives me an error when I try to handle those strings with javascript.

I wrote some jquery code that uses the django variable like this:

new_text = "{{text|safe}}";
$("#text_p").text(new_text);

if I mark it as "safe" then javascript gives me a syntax error:

the text "(error here)word between quotes" the user posted

This is logical because javascript understands the quotes like this:

new_text = "this is the text "word between quotes" the user posted"

So, if I don't mark it as "safe" and let django escape the text, it doesn't give me an error, but the text looks like this:

 the text "word between quotes&quot the user posted

I don't know what to do, and I guess it may not be simple cause if I use single quotes to declare the javascript variable, I will have the same problem when the user posts a text with single quotes. If I use a regex to replace double quotes and not mark the text as "text|safe", then other tags will be escaped and the text will be full of "<br /&gt" etc.

I have an idea that may work but is ugly and probably not the best option: including the text in a <p class = "hidden"> tag and then calling it using jquery.

So, the question is, how do I solve this?, is there a better way? Thanks in advance for your help.

EDIT: I created a Runnable to explain it better.

like image 438
Alejandro Veintimilla Avatar asked Aug 08 '14 21:08

Alejandro Veintimilla


2 Answers

Use escapejs filter. Example:

{{ string|escapejs }}
like image 147
Arti Avatar answered Oct 19 '22 18:10

Arti


Ok, I found a partial solution, hope it helps someone in the future. It is not an elegant solution, so, if anyone has a better option, it will be welcomed.

I included the text that has a "quoted" word inside a html hidden tag.

python-django:
text_with_quotes = 'this is a text and a word between "quotes"'

html:
<p id = "new_text" class = "hidden"> {{text_with_quotes|safe}}</p>

js:
new_text = $("#new_text").text();
$("#text_p").text(new_text);

it works. But there may be a better option using javascript and/or python.

like image 1
Alejandro Veintimilla Avatar answered Oct 19 '22 20:10

Alejandro Veintimilla