catsfw
catsfw

Reputation: 125

Django with Markdown 2.5.2, html output not behaving as expected

I'm working on a web app using Django 1.7.1, and created a markdown filter using the markdown library.

My markdown filter:

from django import template
from markdown import markdown

register = template.Library()


@register.filter(name='markdown')
def markdown_processor(text):
    return markdown(text)

If I pass some string, i.e., "###hey", the browser shows <h3>hey</h3> instead of:

hey

This is what i have in my html file:

{{ my_object.description|markdown }}

I've checked my_object.description to see if it is a unicode string using:

isinstance(my_object.description, unicode)

Upvotes: 0

Views: 567

Answers (3)

Waylan
Waylan

Reputation: 42647

As you have discovered, Django's auto-escaping is the culprit. In addition to the other suggests provided, you can mark a filter as "safe" and then the value returned by that filter will not get escaped (notice the use of is_safe=True):

from django import template
from markdown import markdown

register = template.Library()

@register.filter(name='markdown', is_safe=True)
def markdown_processor(text):
    return markdown(text)

Upvotes: 0

Wenzil
Wenzil

Reputation: 236

As you have found, Django's auto-escape mechanism is what's causing the problem. If you mark the markdown output as safe, Django will not auto-escape it.

from django import template
from markdown import markdown
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter(name='markdown')
def markdown_processor(text):
    return mark_safe(markdown(text))

Upvotes: 2

catsfw
catsfw

Reputation: 125

Got it, I needed the autoescape template tag.

{% autoescape off %}
{{ my_object.description|markdown }}
{% endautoescape %}

Upvotes: 1

Related Questions