Built-in filter "linebreaks" does not do what it says in the documentation

12 views
Skip to first unread message

Daniel Klein

unread,
Jul 16, 2012, 7:43:35 AM7/16/12
to django...@googlegroups.com
So the bog-standard built-in filter linebreaks is supposed to do the following:

"Replaces line breaks in plain text with appropriate HTML"

The doc string is:

 """Converts newlines into <p> and <br />s."""

However, it doesn't do this at all. It neither replaces nor converts; instead it leaves linebreaks in place and ADDS html tags:

return u'\n\n'.join(paras)

I could write my own filter that simply returns join(paras), but there's got to be a better way, no? And shouldn't we try to make the documentation talk about what is actually happening?

Russell Keith-Magee

unread,
Jul 16, 2012, 8:25:44 PM7/16/12
to django...@googlegroups.com
I don't accept your argument that the documentation is incorrect (or
that it's significantly misleading).

If you have plain text with newlines, you will usually want those
newlines preserved in rendered HTML. The way you do that -- the
"appropriate HTML" is to use <br> and <p> elements.

The implementation splits on newline characters, inserts the required
<br> and <p> elements -- and then joins with newlines to preserve
human readability of the output HTML. Newlines are a valid (if
ignored) part of the HTML spec; the newlines in the original markup
have therefore been "replaced" with the "appropriate HTML'.

If you can think of a better phrasing, we're always open to
suggestions. The current description has served us well for several
years, but that doesn't mean we're not willing to improve on it.

As for your actual problem: I'm not sure exactly what you're trying to
achieve -- i.e., why a strict join(paras) is an important operation to
you. Newlines are interpreted as whitespace in HTML, there's no
difference between text with newlines, and text without newlines
(other than human readability of the output).

If you're generating something other than HTML, then you're going to
need to build your own set of template filters; Django's builtin tags
are very much focussed at generating HTML.

Either way, a strict "join" filter isn't that complex -- maybe half a
dozen lines of code all up. If you truly need a strict join(), then
writing your own tag *is* the better way, in this case.

Yours,
Russ Magee %-)
Reply all
Reply to author
Forward
0 new messages