djangodjango-templatesmarkdownurlize

Getting markdown and urlize template tags to play nice


I'm using markdown to format some comments in a Django app.

If I try to combine markdown and urlize, inevitably bad formatting errors happen (links get added where they don't belong or aren't recognized, and of course the errors change depending on which filter I use first).

Basically I'd like a filter that does markdown and automatically turns links into hyperlinks if not done so by markdown.

Otherwise, I suppose I'll have to roll my own filter, which I would so rather not do.


Solution

  • What I do is use the Markdown urlize extension.

    Once installed, you can use it in a Django template like this:

    {{ value|markdown:"urlize" }}
    

    Or in Python code like this:

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

    Here is the start of the Markdown extension docs in case you need more info.