加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

golang html/template

发布时间:2020-12-16 18:38:45 所属栏目:大数据 来源:网络整理
导读:template包(html/template)实现了数据驱动的模板,用于生成可对抗代码注入的安全HTML输出。本包提供了和text/template包相同的接口,无论何时当输出是HTML的时候都应使用本包。 main.go package mainimport ("html/template""io/ioutil""os""time""fmt")fu

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

main.go

package main

import (
	"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")
}

test1.html

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

test2.html

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

模版解析

// 模版解析
func (this *YulanController) parseTemplate(tplname string,data interface{}) (string,error) {
	var html string

	b,err := ioutil.ReadFile(tplname)
	if err != nil {
		fmt.Println(tplname,err)
		return "",err
	}

	t := template.New(tplname)
	template.Must(t.Parse(string(b)))

	wr := bytes.NewBufferString("")
	err = t.Execute(wr,data)
	if err != nil {
		fmt.Println(err)
		return "",err
	}

	return wr.String(),err
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读