html template语言,golang html/template

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

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

template

hello {{.UserName}}

test2.html

template

hello {{.UserName}}

{{tihuan .UserName}}

有疑问加站长微信联系(非本文作者)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值