how to render django template variable as html?

paynestrike picture paynestrike · Dec 25, 2012 · Viewed 13k times · Source

What I want is like stack overflow. User can HTML format their text input, and the page should be rendered exactly in the same way,

I use the wmd.js to store the formatted input, Consider I have a context variable {{variable}} with string value "<p>something</p>". When I render the template,

{{variable}} outputs <p>something</p>

and {{variable|safe}} also output <p>something</p>

It shows the html tag as text in the page. How to render the HTML tag in the {{variable}} but not showing them as plain text.

the template

    <div id='thread_answer_content' >
        {% for answer in question.answer_set.all %}
            {{answer.answerbody|safe}}
        {% endfor %}
    </div>

the view

def detail(request,question_id):
q = get_object_or_404(Question,pk=question_id)
return render_to_response('CODE/detail.html',{'question':q},
        context_instance = RequestContext(request)
    )

here is the django admin page of the question , am using sqlite3 by the way enter image description here

Answer

Pattapong J picture Pattapong J · Dec 27, 2012

use tag : http://docs.djangoproject.com/en/dev/ref/templates/builtins/#autoescape

{% autoescape off %}{{ variable }}{% endautoescape %}