栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

Go语言http/template的嵌套和继承

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Go语言http/template的嵌套和继承

Go语言http/template的嵌套和继承

html/template包实现了数据驱动的模板,用于生成可防止代码注入的安全的HTML内容。它提供了和text/template包相同的接口,Go语言中输出HTML的场景都应使用html/template这个包。

template嵌套

可以在template中嵌套其他的template。这个template可以是单独的文件,也可以是通过define定义的template。

举个例子: t.tmpl文件内容如下:




    
    
    
    tmpl test


    
    

测试嵌套template语法


{{template "ul.tmpl"}}
{{template "ol.tmpl"}} {{ define "ol.tmpl"}}
  1. 吃饭
  2. 睡觉
  3. 打豆豆
{{end}}

ul.tmpl文件内容如下:

  • 注释
  • 日志
  • 测试
template继承
{{block "name" pipeline}} T1 {{end}}

block是定义模板{{define "name"}} T1 {{end}}和执行{{template "name" pipeline}}缩写,典型的用法是定义一组根模板,然后通过在其中重新定义块模板进行自定义。

定义一个根模板templates/base.tmpl,内容如下:




    Go Templates


{{block "content" . }}{{end}}

然后定义一个templates/index.tmpl,”继承”base.tmpl:

{{template "base.tmpl"}}

{{define "content"}}
    
Hello world!
{{end}}

然后使用template.ParseGlob按照正则匹配规则解析模板文件,然后通过ExecuteTemplate渲染指定的模板:

func index(w http.ResponseWriter, r *http.Request){
	tmpl, err := template.ParseGlob("templates*.tmpl")解析模板。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/944773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号