golang template 用作类似mybatis前期一些准备

dingking · · 712 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

背景

在gin融合sqlx包时,发现在写复杂的sql的时候会比较复杂,而在java一直比较钟爱mybatis编写sql,希望在golang也能找到类似的做法,在查阅很多博客看到使用模板进行类似mybatis xml生成sql,所以先把原先学习语法没有进行学习的模板进行一些储备,只是一部分认为能用到的一些知识

使用

导入模板文件
1.导入单个文件

template.ParseFiles("template_test.tpl")

2.导入多个文件(不同dao使用不同文件表示)

template.ParseGlob("*.tpl")

3.加入自定义函数FuncMap
自定义函数必须在文件导入之前加入,否则会出错,因为这个纠结了很久,都是因为不熟悉api

t = template.New("test")
t.Funcs(template.FuncMap{"add": Add}) // 一定要在加载文件之前
t.ParseGlob("*.tpl")

4.编写简单引入
在template_test.tpl写入

{{define "getName"}}
    select * from name where name={{.Name}} and age={{.Age}}
{{end}}

define用作子模块,可以用于dao里面的各个方法命名,同一个文件表达一个dao全部方法
golang进行引入执行

func GetName() {
    fmt.Println(t.Name())
    user := &User{Name: "test", Age: 12}
    t.ExecuteTemplate(os.Stdout, "getName", user)
}

输出select * from name where name=test and age=12
5.编写循环与自定义add方法使用
在template_test.tpl写入

{{define "getNames"}}
    select * from name where 1=1 {{with .Name}}and name={{.}}{{end}} {{with .Ids}}{{range .}} and id={{.}}{{end}} {{end}}
    {{add 1 2}}
{{end}}

注意上面使用了with 后续表示检验是否为空的值直接使用{{.}}
add方法在上面添加自定义函数时候已经引入,下面把定义的函数,与处理其他代码写下

func Add(a int, b int) int {
    return a + b
}
type IDData struct {
    Name interface{}
    Ids  []int
}

func GetNames() {
    fmt.Println(t.Name())
    data := &IDData{Name: "test", Ids: nil}
    err := t.ExecuteTemplate(os.Stdout, "getNames", data)
    if err != nil {
        fmt.Println(err)
    }
}

6.其他内置的一些函数
在template_test.tpl写入

{{define "funcAction"}}
    {{if eq .a 0}}a=0{{else}}a=1{{end}}
    {{if eq .b 0}}b=0{{else if eq .b 1}}b=1{{else}}b={{.b}}{{end}}
    {{if or (eq .a 0) (eq .b 2)}}true{{else}}false{{end}}
    {{if and (eq .a 0) (eq .b 2)}}true{{else}}false{{end}}
{{end}}

上面主要有使用了if eq or and
golang代码

func FuncAction() {
    data := make(map[string]interface{})
    data["a"] = 1
    data["b"] = 2
    if err := t.ExecuteTemplate(os.Stdout, "funcAction", data); err != nil {
        fmt.Println("error", err)
    }
}

最后把测试代码贴下 自己也用作参考

go_template.go

package template

import (
    "bytes"
    "fmt"
    "html/template"
    "os"
)

var t *template.Template

type User struct {
    Name string
    Age  uint
}

func init() {
    //t, _ = template.ParseFiles("template_test.tpl")
    t = template.New("test")
    t.Funcs(template.FuncMap{"add": Add}) // 一定要在加载文件之前
    t.ParseGlob("*.tpl")
}

func Add(a int, b int) int {
    return a + b
}

func GetName() {
    fmt.Println(t.Name())
    user := &User{Name: "test", Age: 12}
    t.ExecuteTemplate(os.Stdout, "getName", user)
}

type IDData struct {
    Name interface{}
    Ids  []int
}

func GetNames() {
    fmt.Println(t.Name())
    data := &IDData{Name: "test", Ids: nil}
    err := t.ExecuteTemplate(os.Stdout, "getNames", data)
    if err != nil {
        fmt.Println(err)
    }
}

func InsertName() {
    fmt.Println(t.Name())
    user := &User{Name: "test", Age: 14}
    buf := new(bytes.Buffer)
    t.ExecuteTemplate(buf, "insertName", user)
    sql := buf.String()
    fmt.Println("InsertName_sql:", sql)
}

func GetNameTwo() {
    fmt.Println(t.Name())
    user := &User{Name: "test", Age: 12}
    t.ExecuteTemplate(os.Stdout, "getName1", user)
}

func InsertNameTwo() {
    fmt.Println(t.Templates()[0].Name())
    user := &User{Name: "test", Age: 14}
    buf := new(bytes.Buffer)
    t.ExecuteTemplate(buf, "insertName1", user)
    sql := buf.String()
    fmt.Println("InsertName_sql:", sql)
}

func FuncAction() {
    data := make(map[string]interface{})
    data["a"] = 1
    data["b"] = 2
    if err := t.ExecuteTemplate(os.Stdout, "funcAction", data); err != nil {
        fmt.Println("error", err)
    }
}

go_template_test.go

package template

import "testing"

func TestGetName(t *testing.T) {
    GetName()
}

func TestInsertName(t *testing.T) {
    InsertName()
}

func TestGetNameTwo(t *testing.T) {
    GetNameTwo()
}

func TestInsertNameTwo(t *testing.T) {
    InsertNameTwo()
}

func TestGetNames(t *testing.T) {
    GetNames()
}

func TestFuncAction(t *testing.T) {
    FuncAction()
}

template_test.tpl

{{define "getName"}}
    select * from name where name={{.Name}} and age={{.Age}}
{{end}}

{{define "insertName"}}
    insert into name (name,age) values ({{.Name}},{{.Age}})
{{end}}

{{define "getNames"}}
    select * from name where 1=1 {{with .Name}}and name={{.}}{{end}} {{with .Ids}}{{range .}} and id={{.}}{{end}} {{end}}
    {{add 1 2}}
{{end}}

{{define "funcAction"}}
    {{if eq .a 0}}a=0{{else}}a=1{{end}}
    {{if eq .b 0}}b=0{{else if eq .b 1}}b=1{{else}}b={{.b}}{{end}}
    {{if or (eq .a 0) (eq .b 2)}}true{{else}}false{{end}}
    {{if and (eq .a 0) (eq .b 2)}}true{{else}}false{{end}}
{{end}}

template_test1.tpl

{{define "getName1"}}
    select * from name1 where name={{.Name}} and age={{.Age}}
{{end}}

{{define "insertName1"}}
    insert into name1 (name,age) values ({{.Name}},{{.Age}})
{{end}}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:dingking

查看原文:golang template 用作类似mybatis前期一些准备

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

712 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传