这里用的goframe v2框架
提醒:下面的import 引入的控制器和api,根据自己实际项目路径
import (
"context"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gzdzh/dzhgo/modules/dzhCms/controller/web"
"github.com/gogf/gf/v2/frame/g"
)
func main() {
s := g.Server()
s.Group("/web", func(group *ghttp.RouterGroup) {
group.Bind(
new(web.CmsIndexController),
)
})
s.Run()
}
package middleware
import (
"context"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gfile"
)
func init() {
s := g.Server()
ctx := context.Background()
// 普通静态文件
if gfile.Exists("./template") {
s.AddStaticPath("/template", "/template")
} else {
g.Log().Debug(ctx, "/template 不存在,创建一个")
if err := gfile.Mkdir("./template"); err != nil {
return
}
}
func IndexMiddleware(r *ghttp.Request) {
indexHtml := gfile.Exists("./template/index.html")
var templateName string
if indexHtml {
templateName = "index.html"
r.SetParam("templateName", templateName)
r.Middleware.Next()
return
}
}
// 预处理首页模版
s.BindMiddleware("/web/index", IndexMiddleware)
}
package v1
import "github.com/gogf/gf/v2/frame/g"
type IndexReq struct {
g.Meta `path:"/index" method:"GET"`
}
package web
import (
"context"
"github.com/gzdzh/dzhgo/dzhCore"
v1 "github.com/gzdzh/dzhgo/modules/dzhCms/api/v1"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gview"
)
type CmsIndexController struct {}
func (c *CmsIndexController) Index(ctx context.Context, req *v1.IndexReq) (res *dzhCore.BaseRes, err error) {
view := gview.New()
// 设置模板目录
err = view.SetPath("template")
if err != nil {
return nil, err
}
view.Assigns(map[string]interface{}{
"name": "john",
"age": 18,
"score": 100,
})
// 渲染模板
content, err := view.Parse(ctx, "index.html")
if err != nil {
panic(err)
}
var r = g.RequestFromCtx(ctx)
r.Response.Writefln(content)
return
}
根目录template的文件夹放模板文件,中间件那里已经映射到该目录了,如果没有该目录,会自动建一个
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>模板引擎渲染</title>
</head>
<body>
<p>Name: {{.name}}</p>
<p>Age: {{.age}}</p>
<p>Score:{{.score}}</p>
</body>
</html>
浏览器打开 http://localhost:端口/web/index