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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM