我们可以使用以下的方式去渲染html

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Main website",
        })
    })
    router.Run(":8080")
}

在html中我们可以使用特殊的双花括号来渲染title这个值

<html>
    <h1>
        {{ .title }}
    </h1>
</html>

值得注意的是这种方式并不是gin特有的,而是golang特有的,它还有其他的模板语法。

模板语法:
定义变量:

{{$article := "hello"}}

也可以给变量赋值

{{$article := .ArticleContent}}

函数的调用:

{{funcname .arg1 .arg2}}

判断语法:

{{if .condition}}
{{end}}
{{if .condition1}}
{{else if .contition2}}
{{end}}
not
{{if not .condition}}
{{end}}
and
{{if and .condition1 .condition2}}
{{end}}
or
{{if or .condition1 .condition2}}
{{end}}
eq 等于
{{if eq .var1 .var2}}
{{end}}
ne 不等于
{{if ne .var1 .var2}}
{{end}}
lt 小于 
(less than){{if lt .var1 .var2}}
{{end}}
le 小于等于
{{if le .var1 .var2}}
{{end}}
gt 大于
{{if gt .var1 .var2}}
{{end}}
ge 大于等于
{{if ge .var1 .var2}}
{{end}}

循环:

{{range $i, $v := .slice}}
{{end}}

引入一个模板:

{{template "navbar"}}
最后编辑: Simon  文档更新时间: 2022-03-13 15:08   作者:Simon