1

I've got a bunch of HTML:

<div align="center" id="whatever">
<a href="http://www.whatever.com" style="text-decoration:none;color:black">
<img src="http://www.whatever.com/images/whatever.jpg" />
</a></div>

I want to output it all as literal HTML in the browser, i.e. display the above to the user. (EDIT: unfortunately I don't have access to Django variables in my template, due to the quirks of the system I'm working on, so I can't use {{ | escape }}.

Is there any way to do this, either using Django template tags or a special HTML tag, without having to HTML-escape it all by hand?

Thanks!

4 Answers 4

3

If the HTML has to be included in the template itself, you can use the filter block:

{% filter force_escape %}
    <div align="center" id="whatever">
    <a href="http://www.whatever.com" style="text-decoration:none;color:black">
    <img src="http://www.whatever.com/images/whatever.jpg" />
    </a></div>
{% endfilter %}

Documentation

Sign up to request clarification or add additional context in comments.

Comments

1

You can always just escape it yourself if you don't wan't to do it in the template and it's somehow not escaped (let's just say the template author used {{ var|safe }})

from django.utils.html import escape

escaped_html = escape(my_html)

1 Comment

PS: I see now, I somehow read that you don't have access to the template, not that you don't have access to variables in the template.
0

Yup, just use the escape filter:

{{my_html|escape}}

Edit: force_escape:

{% filter force_escape %}
   ... your HTML to be escaped ...
{% endfilter %}

Or, from Python:

from django.utils.html import escape
escaped_html = escape(html_to_escape)

3 Comments

Sorry - due to the quirks of the particular system I'm working with, I don't actually have the ability to put variables in the Django template. I could escape the entire string, but it's kinda long. Is there any other way?
That's a no-op under normal conditions. As AndiDog says in his answer, Django auto-escapes by default. It has done since before 1.0 was released.
Ah, well, in that case, use the force_escape filter (see edits).
0

Django defaults to auto-escape context variables when inserting them (see also the documentation). So unless you marked the variable as safe, or use the autoescape off template tag, just use {{ contextVariable }}.

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.