views:

43

answers:

2

I'm looking for a Django template filter that turns a multi-line construction into one big line. Has anyone implemented it? The reason is - I have a form, {{form.as_p}} creates a multi-line html fragment, I want to create a javascript variable which is an html fragment, but when I do like this:

var new_div_text = '{{form.as_p}}';

it doesn't work. The reason is obvious, in javascript constructions like

var hello = 'Hello
world';    

are invalid!

A: 

Check out this template filter to remove newlines from a text block.

aeby
+2  A: 

Reading your use case, it doesn't appear that you just want to remove lines. What if one of your form labels contains a ' character? Oops, your javascript is now invalid. Django comes with a filter called escapejs which us used for precisely this problem.

With escapejs, you would type:

var newDivText = '{{ form.as_p|escapejs }}'

and you won't have to worry about any characters destroying your javascript.

Mike Axiak
Exactly! I didn't think about single-quote escaping, because as_p uses double-quotes, not single-quotes, but as I see now, escapejs is really what I need!
Graf