Literal HTML in Django without using a variable?

会有一股神秘感。 提交于 2019-12-24 10:37:00

问题


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!


回答1:


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)



回答2:


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




回答3:


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)



回答4:


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



来源:https://stackoverflow.com/questions/5042820/literal-html-in-django-without-using-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!