golang echo 代碼詳解之模版篇

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。在 echo 裡使用模版則必須先註冊一個,如果不註冊就會報出下面這樣的錯誤```json{"time":"2017-12-12T23:03:57.939138716+08:00","level":"ERROR","prefix":"echo","file":"echo.go","line":"284","message":"Renderer not registered"}```註冊就是給 echo.Renderer 賦值。echo 的 Renderer 屬性是一個介面```goRenderer interface {Render(io.Writer, string, interface{}, Context) error}```### 一、使用標準庫模版echo 的文檔給出了使用官方模版註冊的方式```go// 實現 Renderer 介面type Template struct { templates *template.Template}func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error { return t.templates.ExecuteTemplate(w, name, data)}// 處理 view 目錄下的檔案產生對應的模版// 關於 ExecuteTemplate 和 ParseGlob 方法可以查看 // https://wizardforcel.gitbooks.io/golang-stdlib-ref/content/67.html#Template.ExecuteTemplatet := &Template{templates: template.Must(template.ParseGlob("public/views/*.html")),}// 賦值e.Renderer = t```### 二、使用 pongo2`gopkg.in/flosch/pongo2.v3` 是一個很不錯的模版引擎,很多時候會選擇它來渲染模版。首先還是實現 Renderer 介面```gotype Template struct { // 這裡使用一個 map 來儲存預先處理了的模版tmplMap map[string]*pongo2.Template}func (t *Template) Render(w io.Writer, templateName string, data interface{}, c echo.Context) error { // 這雷根據傳來的 name 從 tmplMap 裡尋找模版來渲染 // 注意 ExcuteWriter 的參數必須是 map[string]interface{} 的dataMap := data.(map[string]interface{})template, exist := t.tmplMap[templateName]if !exist {return errors.New("template " + templateName + " not found")}return template.ExecuteWriter(dataMap, w)}```然後先行編譯模版```go// 讀取目錄下的檔案預先處理func preCompile(dir string) *Template {tmplMap := make(map[string]*pongo2.Template)dirPath := filepath.Dir(dir)fileInfos, _ := ioutil.ReadDir(dirPath)for _, fileInfo := range fileInfos {t, err := pongo2.FromFile(path.Join(dir, fileInfo.Name()))if err != nil {log.Fatalf("\"%s\": %v", fileInfo.Name(), err)}tmplMap[strings.Replace(fileInfo.Name(), path.Ext(fileInfo.Name()), "", -1)] = t}return &Template{tmplMap}}```最後賦值```gofunc NewTemplates(dir string) *Template {return preCompile(dir)}t := NewTemplates("./views/")e.Renderer = t```這樣自訂的 renderer 就算完成了。原文地址:[laily.net](https://laily.net/article/golang%20echo%20%E4%BB%A3%E7%A0%81%E8%AF%A6%E8%A7%A3%E4%B9%8B%E6%A8%A1%E7%89%88%E7%AF%87)1172 次點擊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.