简体   繁体   English

如何在 Django 模板中将变量显示为 HTML?

[英]How To show variable as HTML in Django template?

let's said that I have function假设我有功能

def func(request):
    a="Hello, <br> this is my first app"
    return render_to_response(
                            'home.html',
                            {'a':a, 'request':request},
                            context_instance=RequestContext(request)
                          )

when I load variable a in home.html as当我将 home.html 中的变量 a 加载为

{{a}} {{一种}}

I will get Hello, <br> this is my first app , how to present <br> as new line in django template ...??我会得到你好, <br>这是我的第一个应用程序,如何将<br>为 django 模板中的新行...??

Try this:尝试这个:

from django.utils.safestring import mark_safe


a = mark_safe("Hello, <br> this is my first app")

Django automatically escapes any HTML in your variables, so you need to mark it as a safestring. Django 会自动转义变量中的任何 HTML,因此您需要将其标记为安全字符串。

Keep in mind, for example, that safestring + unsafestring = unsafestring.例如,请记住,safestring + unsafestring = unsafestring。 You can read more about it here你可以在这里阅读更多关于它的信息

An easier way would be to use一种更简单的方法是使用

{{a|safe}}

in the template itself.在模板本身中。

在模板文件中使用 {{a|safe}},而不是 {{a}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM