Scott Skiles
Scott Skiles

Reputation: 3847

Render Markdown to HTML while preserving headers, newlines, etc.?

Happy New Year! I have started out my new year by making a resolution to get Markdown rendering to HTML working for my Django blog. I came across Django Markdownify and it is pretty OK! I managed to get my markdown file rendered, via get_context_data as described below in installation and usage:

views.py

class MarkDown(TemplateView):
  template_name = 'index.html'

  def get_context_data(self, **kwargs):
      markdowntext = open(os.path.join(os.path.dirname(__file__), 'templates/test.md')).read()

      context = super(MarkDown, self).get_context_data(**kwargs)
      context['markdowntext'] = markdowntext

      return context

index.html

{% load markdownify %}
{{ markdowntext|markdownify }}

Although basic rendering works, there are some major drawbacks. Including:

  1. Inability to recognize headers (e.g. ### in ### My Header gets stripped completely)
  2. Poor handling of new lines (whitespace is not respected in any form, but blockquotes work for newlines (>))

These two issues alone are enough to give me pause and seek out an alternative solution for Markdown to HTML in Django. I did open an issue for the header problem and I'll wait to hear back. Until then, if anyone can recommend some Django specific workarounds I'd greatly appreciate it.

Upvotes: 1

Views: 850

Answers (2)

emorling
emorling

Reputation: 157

Add this to your settings.py and it should work fine.

MARKDOWNIFY_WHITELIST_TAGS = [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'em',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'i',
'li',
'ol',
'p',
'strong',
'ul'
]

Upvotes: 0

Oleg Russkin
Oleg Russkin

Reputation: 4404

Brief summary of google results on topic:

Django Integrated Markdown Editors - allow editing and previewing markdown and possibly other formats. Maybe not so lightweight. Usually provide best html escaping:

Django Fields with Markdown support:

Other:

Upvotes: 1

Related Questions