开发者

Literal HTML in Django without using a variable?

开发者 https://www.devze.com 2023-02-11 17:12 出处:网络
I\'ve got a bunch of HTML: <div align=\"center\" id=\"whatever\"> <a href=\"http://www.whatever.com\" style=\"text-decoration:none;color:black\">

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!


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


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)


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)


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 }}.

0

精彩评论

暂无评论...
验证码 换一张
取 消