English 中文(简体)
How do I make django s markdown filter transform a carriage return to <br />?
原标题:

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

最佳回答

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 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" }}

问题回答

EDIT: As of the end of June, 2011, the extension below is now included with Python Markdown.

Here is a Markdown extension that I wrote and am currently testing on my site to do exactly what you want:

"""
A python-markdown extension to treat newlines as hard breaks; like
StackOverflow and GitHub flavored Markdown do.

"""
import markdown


BR_RE = r 
 

class Nl2BrExtension(markdown.Extension):

    def extendMarkdown(self, md, md_globals):
        br_tag = markdown.inlinepatterns.SubstituteTagPattern(BR_RE,  br )
        md.inlinePatterns.add( nl , br_tag,  _end )


def makeExtension(configs=None):
    return Nl2BrExtension(configs)

I put this in a file called mdx_nl2br.py and put it on my PYTHONPATH. You can then use it in a Django template like this:

{{ value|markdown:"nl2br" }}

If you d like to use it in regular code, you can do something like this:

import markdown
md = markdown.Markdown(safe_mode=True, extensions=[ nl2br ])
converted_text = md.convert(text)

Here is the starting point in the docs for using and writing extensions.

You can override default MARKDOWN_DEUX_STYLES with adding "break-on-newline": True in extras settings :

MARKDOWN_DEUX_STYLES = {
    "default": {
        "extras": {
            "code-friendly": None,
            "break-on-newline": True,
        },
        "safe_mode": "escape",
    }
}

Documentation of python-markdown2:

break-on-newline: Replace single new line characters with
when True.

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

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





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签