unrolled/render 集成Masterminds/sprig 增强模版处理

Masterminds/sprig 是一个强大的golang 模版函数,以下是一个unrolled/render 集成Masterminds/sprig 的简单demo

环境准备

  • go.mod
module github.com/rongfengliang/renameio-app
go 1.14
require (
    github.com/Masterminds/goutils v1.1.0 // indirect
    github.com/Masterminds/semver v1.5.0 // indirect
    github.com/Masterminds/sprig v2.22.0+incompatible
    github.com/google/renameio v0.1.0
    github.com/google/uuid v1.1.1 // indirect
    github.com/huandu/xstrings v1.3.2 // indirect
    github.com/imdario/mergo v0.3.10 // indirect
    github.com/mitchellh/copystructure v1.0.0 // indirect
    github.com/stretchr/testify v1.6.1 // indirect
    github.com/unrolled/render v1.0.3
    golang.org/x/crypto v0.0.0-20200728195943-123391ffb6de // indirect
)
  • 项目结构
├── demo.conf
├── go.mod
├── go.sum
├── main.go
└── templates
    ├── admin
    ├── home
    ├── index.tmpl
    └── layout.tmpl

golang 代码集成

  • main.go
package main
import (
    "encoding/xml"
    "errors"
    "html/template"
    "net/http"
    "github.com/Masterminds/sprig"
    "github.com/google/renameio"
    "github.com/unrolled/render"
)
// fielname for test
func filname() error {
    confContent := `
    nginx {
        main {
            server {
                port :9090;
            }
        }
    }
    `
    err := renameio.WriteFile("./demo.conf", []byte(confContent), 0644)
    if err != nil {
        return errors.New("some wrong:" + err.Error())
    }
    return nil
}
// render demo
func main() {
    r := render.New(render.Options{
        Layout:        "layout",
        IsDevelopment: true,
        Funcs: []template.FuncMap{
            sprig.FuncMap(),
        },
    })
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Write([]byte("Welcome, visit sub pages now."))
    })
    ob := struct {
        XMLName xml.Name `json:"-" xml:"dalongdemoapp"`
        Name    string   `json:"dalongrong" xml:"dalongdemo"`
        Items   []string `json:"items" xml:"items"`
    }{
        Name:  "dalong",
        Items: []string{"demo", "app"},
    }
    mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
        r.JSON(w, 200, ob)
    })
    mux.HandleFunc("/xml", func(w http.ResponseWriter, req *http.Request) {
        r.XML(w, 200, ob)
    })
    mux.HandleFunc("/rename", func(w http.ResponseWriter, req *http.Request) {
        if err := filname(); err != nil {
            r.JSON(w, 500, "rename wrong")
            return
        }
        r.JSON(w, 200, "rename ok")
    })
    mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
        r.HTML(w, 200, "index", ob)
    })
    http.ListenAndServe("127.0.0.1:3000", mux)
}
 
  • index.tmpl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{.Name}}
    {{ range .Items }}
            <p>{{ . }}</p>
    {{ end }}
    {{ "hello!" | repeat 5 }}
    {{ range $i,$v := .Items }}
           <p>{{ $i }} {{$v}}</p>
    {{ end }}
</body>
</html>
  • layout.tmpl
<!-- templates/layout.tmpl -->
<html>
  <head>
    <title>My Layout</title>
    <!-- Render the partial template called `css-$current_template` here -->
    {{ partial "css" }}
  </head>
  <body>
    <!-- render the partial template called `header-$current_template` here -->
    {{ partial "header" }}
    <!-- Render the current template here -->
    {{ yield }}
    This is the {{ current }} page.
    <!-- render the partial template called `footer-$current_template` here -->
    {{ partial "footer" }}
  </body>
</html>
 
  • 运行效果
go run main.go

集成模版函数的demo

说明

以上只是一个简单的集成,实际上sprig 还是很强大的,helm就集成了此模块
效果

参考资料

https://github.com/Masterminds/sprig
https://github.com/unrolled/render

原文地址:https://www.cnblogs.com/rongfengliang/p/13401340.html