默认情况下,Go语言引用HTML文件,HTML文件中使用{{ }}
,使用Delims
参数可以修改默认的符号
目录结构:
main.go
index.html
main.go内容
package main
import (
"fmt"
"html/template"
"net/http"
)
func index(w http.ResponseWriter, r *http.Request) {
//使用Delims参数可修改默认符号
//定义模板
//解析模板
t,err := template.New("index.tmpl").Delims("{[","]}").ParseFiles("./index.tmpl")
if err !=nil {
fmt.Printf("parse template failed,err%v",err)
return
}
//渲染模板
name := "Go语言"
t.Execute(w,name)
}
func main() {
http.HandleFunc("/index",index)
err := http.ListenAndServe(":9000",nil)
if err !=nil {
fmt.Printf("HTTP server start failed,err%v",err)
return
}
}
index.tmpl内容
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>修改默认符号模板</title>
</head>
<body>
{{/* 这里把默认的{{}}改成{[]},与main.go代码中Delims定义的一致 }}*/}}
{[. ]}
</body>
</html>
运行代码:
go run main.go
打开浏览器http://ip:9000/index