Gin框架静态文件处理
Gin框架静态文件处理
一、静态文件处理
当我们渲染的HTML文件中引用了静态文件时,我们只需要按照以下方式在渲染页面前调用gin.Static方法即可。
func main() {
r := gin.Default()
r.Static("/static", "./static")
r.LoadHTMLGlob("templates/**/*")
// ...
r.Run(":8080")
}
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
// 加载静态文件
r.Static("/css", "../statics")
r.LoadHTMLFiles("../templates/index.tmpl")
r.GET("/index/css", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
// H is a shortcut for map[string]interface{}
//type H map[string]interface{}
// 渲染模板
"title": "gin渲染模板",
})
})
r.Run(":9999")
}
模板
# index.css
body{
background-color: #ff002f;
}
{{/* 引用css静态文件*/}}
users/index
{{.title}}
二、script文件处理
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
// 加载静态文件
r.Static("/css", "../statics")
r.LoadHTMLFiles("../templates/index.tmpl")
r.GET("/index/css", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
// H is a shortcut for map[string]interface{}
//type H map[string]interface{}
// 渲染模板
"title": "gin渲染模板",
})
})
r.Run(":9999")
}
模板
// index.js文件
alert("js渲染")
{{/* 引用css静态文件*/}}
users/index
{{.title}}
https://sc.chinaz.com/