Reputation: 153
I have a model in Django with a TextField
. I want to pass the info from that TextField
onto a webpage through
return render(request, 'index.html', {
'textFieldValue': textFieldValue,
'context': RequestContext(request),
})
The problem I'm having is that since the TextField
can contain new lines, when it's passed onto my webpage by doing:
var textFieldValue = "{{ textFieldValue }}";
It becomes:
var textFieldValue = "Testing string is this.
New line abcde
Second new lineabcde";
Which will return an error due to the fact that there are several lines in the TextField
and thus breaking the JavaScript var templates.. Is there a way to fix this? Would I need to split the string into an array of each line, then pass that into my webpage, and have a function to parse through that?
I also tried:
var textFieldValue = "{{ textFieldValue|safe }}";
But it's the same thing.
I want to do this because I want to paste this into a textarea
on my page, which looks like what the TextField
is supposed to show in Django admin.
I imagine that there will be problems in the future with symbols like "
, or '
quotations, and @#
etc.
What would be the best way for me to do this?
Upvotes: 1
Views: 75
Reputation: 13188
You can use Django's built in escapejs
filter (docs here):
{{ value|escapejs }}
e.g, If value is
"testing\r\njavascript \'string" <b>escaping</b>"
, the output will be"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E"
.
Note: This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.
Upvotes: 1