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" 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 />" 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.
Use escapejs
filter.
Example:
{{ string|escapejs }}
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.
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