美文网首页
Django模板[HTML转义]

Django模板[HTML转义]

作者: 錦魚 | 来源:发表于2018-11-02 13:37 被阅读0次

    HTML转义

    • 模板对上下文传递的字符串进行输出时,会对以下字符自动转义。
    • 小于号< 转换为 &lt;
    • 大于号> 转换为 &gt;
    • 单引号' 转换为 &#39;
    • 双引号" 转换为 &quot;
    • 与符号& 转换为 &amp;

    示例

    1)打开booktest/views.py文件,创建视图html_escape。
    def html_escape(request):
       context={'content':'<h1>hello world</h1>'}
       return render(request,'booktest/html_escape.html',context)
    
    2)打开booktest/urls.py文件,配置url。
    url(r'^html_escape/$', views.html_escape),
    
    3)在templates/booktest/目录下创建html_escape.html。
    <html>
    <head>
        <title>转义</title>
    </head>
    <body>
        自动转义:{{content}}
    </body>
    </html>
    
    4)运行服务器,在浏览器中输入如下网址。

    http: //127.0.0.1:8000/html_escape/

    转义后标记代码不会被直接解释执行,而是被直接呈现,防止客户端通过嵌入js代码攻击网站.


    关闭转义

    • 过滤器escape可以实现对变量的html转义,默认模板就会转义,一般省略。
      {{t1|escape}}
    • 过滤器safe:禁用转义,告诉模板这个变量是安全的,可以解释执行。
      {{data|safe}}

    1)修改templates/booktest/html_escape.html代码如下。

    <html>
    <head>
        <title>转义</title>
    </head>
    <body>
        自动转义:{{content}}
    <hr>
        过滤器safe关闭转义:{{content|safe}}
    </body>
    </html>
    

    标签autoescape:

    设置一段代码都禁用转义,接受on、off参数。

    {%autoescape off%}
    ...
    {%endautoescape%}

    1)修改templates/booktest/html_escape.html代码如下。

    字符串字面值对于在模板中硬编码的html字符串,不会转义。

    1)修改templates/booktest/html_escape.html代码如下:
    <html>
    <head>
        <title>转义</title>
    </head>
    <body>
    自动转义:{{content}}
    <hr>
    过滤器safe关闭转义:{{content|safe}}
    <hr>
    标签autoescape关闭转义:
    {%autoescape off%}
        {{content}}
    {%endautoescape%}
    <hr>
    模板硬编码不转义:{{data|default:'<b>hello</b>'}}
    <hr>
    模板硬编码手动转义:{{data|default:"&lt;b&gt;123&lt;/b&gt;"}}
    </body>
    </html>

    相关文章

      网友评论

          本文标题:Django模板[HTML转义]

          本文链接:https://www.haomeiwen.com/subject/alnqxqtx.html