how to render django template variable as html?

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

Answers


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

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

You may want to use escape to render it, instead of safe.

{{ variable|escape }}

For simple HTML formatting, use <p>{{something}}</p>. And the Javascript way is,

<script type="text/javascript">
    var variable  =  "<p>{{something}}</p>";
    document.write(variable);
</script>

If that {{something}} itself contains the HTML tags, then {{something|safe}} itself should work unless you have {% autoescape on %}. For more filtering and formatting refer Built-in template tags and filters.


I think another approach for this is to use the firstof tag:

Note that the variables included in the firstof tag will not be escaped. This is because template tags do not escape their content. Any HTML or Javascript code contained in the printed variable will be rendered as-is, which could potentially lead to security issues. If you need to escape the variables in the firstof tag, you must do so explicitly

{% firstof variable %}

Need Your Help

What does google-services.json really do?

android json google-analytics google-play-services google-cloud-messaging

I work on adding Google Analytics and GCM services to my current app.

Resizing UITextView

iphone uitextview

I have a UITextView added on my UIView. The textview added is not editable, it is just to display some data. The data displayed in the textview is dynamic. Thats is the number of lines is not fixed...