views:

307

answers:

3

How can I change the default behavior in the markdown filter so that it transforms a newline to a br tag?

A: 

You could write a custom filter that calls markdown, then does replace on its output.

John Paulett
+1  A: 

I don't think messing around with the newline syntax is a good idea ...

I agree with Henrik's comment. From the markdown docs:

When you do want to insert a <br /> break tag using Markdown, you end a line with two or more spaces, then type return.

Yes, this takes a tad more effort to create a <br />, but a simplistic “every line break is a <br />” rule wouldn’t work for Markdown. Markdown’s email-style blockquoting and multi-paragraph list items work best — and look better — when you format them with hard breaks.

Have you looked at the other Django markup options, textile and restructuredtext? Their syntax might suit you better.


but if you still want to ...

A rough and ready method is to chain the markdown and linebreaksbr filters.

{{ value|markdown|linebreaksbr }}

This runs the markdown filter, then the linebreaksbr filter, which replaces \n with <br />. You'll probably end up with too many linebreaks, but that might be better for you than too few.

If you a better solution than that, you could

  1. Write a custom filter, as John suggests in his answer.

  2. Dive into the the python-markdown library, which Django uses, and write an extension that implements your desired newline syntax. You would then use the extension with the filter

    {{ value|markdown:"linebreakextension" }}

Alasdair
+1 for solution 2. But that is a filter, not a template tag
vikingosegundo
@vikingosegundo Good catch, now fixed.
Alasdair
A: 

There appears to be a linebreaks filter that converts \n characters to either <br> or <p>.
See linebreaks or linebreaksbr.

Simon Callan