Search code examples
pythonhtmldjangomarkdown

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.


Solution

  • 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: