0

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)

3 Answers 3

2

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))
Sign up to request clarification or add additional context in comments.

Comments

1

Got it, I needed the autoescape template tag.

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.