I’m fetching data from mysql longtext field. And it can contain new lines.
This data is passed to the template where I assigns this longtext data to a javascript variable. The problem I get now is that it will complain about unterminated string literal.
Which is because it tries to assign data in this way
$("#id_review").val("kokokoeoarkgeorkgeorkgeorkg
er
g
gerag
earg
ea
gae
gr
er
gea
g
ear
ge
gae
rg
eagr
kok")
I tried to write a custom filter that will add "+ to the end of each line, but it didn’t work out too well. So I wonder can this problem be fixed somehow?
My attempt on a filter
@register.filter
def escapenewline(value):
return value.replace('\n', '\"+')
Use a JSON encoder to create a valid string which you can use in your JavaScript code.
From a quick search Django doesn’t seem to have a template filter for this but it shouldn’t be too hard to add. Assuming your json filter is called
tojsonthe code in the template would look like this:Here’s how the filter could look like: