html/template 模板工具包在渲染前会对变量内容( html 标签、url 等数据 )进行安全性替换,导致我们无法输出想要的 html 标签。
如 :
package main
import (
	"fmt"
	"html/template"
	"net/http"
)
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		a := `<a href="https://www.lesscode.work/">www.lesscode.work</a>`
		t := template.New("index.html")
		t, err := t.ParseFiles("./templates/index.html")
		if err != nil {
			fmt.Printf("err: %v\n", err)
		}
		t.Execute(w, map[string]any{"a": a})
	})
	http.ListenAndServe(":8080", nil)
}
<html>
<body>
    {{.a}}
</body>
</html>以上代码运行后会原样输出 a 标签的文本内容,而不会渲染一个 a 标签 :
<html>
<body>
    <a href="https://www.lesscode.work/">www.lesscode.work</a>
</body>
</html>可以通过 template.HTML() 函数来实现输出一个 html 标签的功能。
package main
import (
	"fmt"
	"html/template"
	"net/http"
)
func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		a := `<a href="https://www.lesscode.work/">www.lesscode.work</a>`
		t := template.New("index.html")
		t, err := t.ParseFiles("./templates/index.html")
		if err != nil {
			fmt.Printf("err: %v\n", err)
		}
		t.Execute(w, map[string]any{"a": template.HTML(a)})
	})
	http.ListenAndServe(":8080", nil)
}可以通过 template.CSS() 函数来实现输出一段样式的功能。
可以通过 template.JS() 函数来实现输出一段JS代码的功能。
可以通过 template.URL() 函数来实现输出url数据的功能( 比如一个 base64 格式的图片数据 )。