Home > Web Front-end > HTML Tutorial > golang html/template_html/css_WEB-ITnose

golang html/template_html/css_WEB-ITnose

WBOY
Release: 2016-06-24 11:35:56
Original
1746 people have browsed it

template包(html/template)实现了数据驱动的模板,用于生成可对抗代码注入的安全HTML输出。本包提供了和text/template包相同的接口,无论何时当输出是HTML的时候都应使用本包。

main.go

package mainimport (	"html/template"	"io/ioutil"	"os"	"time"	"fmt")func main() {	t := template.New("第一个模板").Delims("[[", "]]") //创建一个模板,设置模板边界	t, _ = t.Parse("hello,[[.UserName]]\n")       //解析模板文件	data := map[string]interface{}{"UserName": template.HTML("<script>alert('you have been pwned')</script>")}	t.Execute(os.Stdout, data) //执行模板的merger操作,并输出到控制台	t2 := template.New("新的模板")                         //创建模板	t2.Funcs(map[string]interface{}{"tihuan": tihuan}) //向模板中注入函数	bytes, _ := ioutil.ReadFile("test2.html")          //读文件	template.Must(t2.Parse(string(bytes)))             //将字符串读作模板	t2.Execute(os.Stdout, map[string]interface{}{"UserName": "你好世界"})	fmt.Println("\n", t2.Name(), "\n")	t3, _ := template.ParseFiles("test1.html") //将一个文件读作模板	t3.Execute(os.Stdout, data)	fmt.Println(t3.Name(), "\n") //模板名称	t4, _ := template.ParseGlob("test1.html") //将一个文件读作模板	t4.Execute(os.Stdout, data)	fmt.Println(t4.Name())}//注入模板的函数func tihuan(str string) string {	return str + "-------" + time.Now().Format("2006-01-02")}
Copy after login



test1.html

<!DOCTYPE html><html><head>	<title>template</title></head><body>hello {{.UserName}}<br></body></html>
Copy after login



test2.html

<!DOCTYPE html><html><head>	<title>template</title></head><body>hello {{.UserName}}<br>{{tihuan .UserName}}</body></html>
Copy after login




Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template