Go html/template的使用

  1. 基础操作

    /*
    读取单个文件,调用Excute函数渲染
    */
    r.GET("/tmp", func(ctx *gee.Context) {
        temp:=template.Must(template.ParseFiles("./static/index.html"))
        log.Println(temp.Execute(ctx.Writer,gee.H{"name":"Ocean"}))
    })
    
    
    /*
    读取多个文件,调用ExecuteTemplate指定文件名渲染
    注意,如果读取了多个文件,且使用Execute,智慧渲染第一个模板
    由此可见:
    1. ExecuteTemplate就是根据模板名指定渲染哪一个模板
    2. 一个template对象中能够保存多个模板文件,使用文件名dirname()进行分隔
    */
    r.GET("/tmp",func(ctx *geeContext){
        temp:=template.Must(template.ParseFiles("./static/index.html",
                                               "./static/index2.html"))
        
        log.Println(
            temp.ExecuteTemplate(ctx.Writer,"index.html",gee.H{
                "name":"ocean"
            }
        )
    })
    
    /*
    想要读取文件夹下所有的文件
    使用ParseGlob()函数,支持正则表达式
    */
    r.GET("/tmp", func(ctx *gee.Context) {
    		temp:=template.Must(template.ParseGlob("./static/*.html"))
    		log.Println(
                temp.ExecuteTemplate(
                    ctx.Writer,"index.html",
                    gee.H{"name":"Ocean"}))
    	})
    
  2. template缓存操作

    我们在程序启动时,就把所有要加载的文件全都读取到内存中。这样用户在访问时,就不需要执行IO操作,读取某个文件->生成template

    func (engine *Engine)LoadHTMLGlob(pattern string){
    	/*
    	分析:
    	1. template.Must() 让template对象的加载,如果加载不到,就产生panic
    	2. template。New() 产生template对象
    	3. Funcs() 添加模板函数,engine中的funcMap是个map类型里面能够保存多个模板函数
    	4. ParseGlob() 将pattern中的文件全都读取出来,按照name,存入engine.htmlTemplates中(每个里面都携带了自定义模板函数)
    	*/
    	engine.htmlTemplates=template.Must(
    		template.New("").
    			Funcs(engine.funcMap).
    			ParseGlob(pattern))
    }
    
    // 主函数中,读取所有模板文件储存到engine对象中
    r.LoadHTMLGlob("./templates/*")
    
    //调用时,从engine对象的htmlTemplates成员变量中,调用ExecuteTemplate读取文件
    if err:=c.engine.htmlTemplates.ExecuteTemplate(c.Writer,name,data);err!=nil{
    		c.Fail(500,err.Error())
    	}
    
posted @ 2020-03-13 16:22  是阿江啊  阅读(2942)  评论(0编辑  收藏  举报