美文网首页
golang gin框架的操作

golang gin框架的操作

作者: 南苑bert | 来源:发表于2020-04-22 17:07 被阅读0次

1. gin template的指定元素

type Indexs struct {
    ID      uint   `json:"id"`
    Classid uint   `json:"classid"`
    Title   string `json:"title"`
    Detail  string `json:"detail"`
    Img     string `json:"img"`
    *dao.Com
}

func GetAllTodo() (todoList []*Indexs, err error) {

    if err = dao.Dbs.Find(&todoList).Error; err != nil {
        return nil, err
    }
    return
}

controllers/index.go



    todoList, err := models.IndexCode("id", ">=", "1")

    data, errs := models.QueryClassAlls()

    if err != nil {
        fmt.Printf("models IndexCode failed,err:%v", err)
        return
    }

    if errs != nil {
        fmt.Printf("modelds QueryClassAlls failed,err:%v", errs)
        return
    }

c.HTML(http.StatusOK, "index.tmpl", gin.H{
        "data":  todoList,
        "title": data,
    })

temp/index.tmpl

  {{- (index .title 0).Detail -}}

2. gin自定义函数使用

func SetupRouter() *gin.Engine {
    r := gin.Default()

    r.Static("/static", "static")

    r.SetFuncMap(template.FuncMap{
        "Remainder": tools.Wrtools,
    })

    r.LoadHTMLGlob("temp/*")

    var index = r.Group("index")

    r.GET("/", controller.IndexHandler)


** tools.go **

package tools

/* Is function int % int = intger(result) */
func Wrtools(r int) bool {
    if r%2 == 0 {
        return true
    } else {
        return false
    }
}

image.png

相关文章

网友评论

      本文标题:golang gin框架的操作

      本文链接:https://www.haomeiwen.com/subject/hkcwihtx.html