【问题标题】:Go html/template & escaping转到 html/模板和转义
【发布时间】:2021-02-18 19:55:25
【问题描述】:

根据html/template 文档中的示例,我不能说我完全理解为什么在我的实验中出现小于和大于不一致的转义: https://golang.org/pkg/html/template/#hdr-Introduction

这是否需要报告错误?我推迟了,因为我对 Go 比较陌生。

$ go version
go version go1.16 linux/amd64

我在go1.15.8 看到了类似的行为。

package main

import (
        htmltemplate "html/template"
        "os"
        texttemplate "text/template"
)

type MyVars struct {
        Flavor string
}

func main() {
        Vars := MyVars{
                Flavor: "#####   html   #####",
        }

        htmlTmpl, _ := htmltemplate.ParseFiles("index.html")
        htmlTmpl.Execute(os.Stdout, Vars)

        Vars = MyVars{
                Flavor: "#####   text   #####",
        }

        textTmpl, _ := texttemplate.ParseFiles("index.html")
        textTmpl.Execute(os.Stdout, Vars)
}
$ cat index.html
{{ .Flavor }}
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
< span >Hello< /span >
<span>Hello</span>
{{ "<" }}span{{ ">" }}Hello{{ "<" }}/span{{ ">" }}
$ ./experiment                                                                                                                                                                                                    
#####   html   #####
&lt;?xml version="1.0" encoding="UTF-8" standalone="no"?> # Why is only < escaped?
&lt; span >Hello&lt; /span >                              # Why is only < escaped?
<span>Hello</span>                                        # Why is neither < nor > escaped?
&lt;span&gt;Hello&lt;/span&gt;
#####   text   #####
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
< span >Hello< /span >
<span>Hello</span>
<span>Hello</span>

【问题讨论】:

    标签: html go templates escaping auto


    【解决方案1】:
    1: {{ .Flavor }}
    2: <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    3: < span >Hello< /span >
    4: <span>Hello</span>
    5: {{ "<" }}span{{ ">" }}Hello{{ "<" }}/span{{ ">" }}
    

    第 2 行和第 3 行的 &amp;lt; 是文本。 HTML 模板包在文本中转义 &amp;lt;,以防止文档阅读器将 &amp;lt; 误解为标记的开头。

    第 2 行和第 3 行的 &gt; 按原样写入输出。转义 &gt; 没有安全优势。

    第 4 行的 &amp;lt;&gt; 是标签的一部分。标签不会被转义。

    第 5 行的 &amp;lt;&gt; 是表达式的值。 HTML 模板包完全转义表达式结果。

    【讨论】:

    • 感谢您的快速反馈。我怀疑这可能是类似的东西。如果不出意外,更新文档以说明我使用的调用与现有示例的行为差异可能会有所帮助。
    • 文档省略了一个细节:文本文字 &amp;lt; 被转义为 &amp;lt;。其他所有内容都记录在案或在示例中显示。
    猜你喜欢
    • 1970-01-01
    • 2011-06-09
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2023-03-24
    相关资源
    最近更新 更多