有人利用Go的html/template
实现了用于管理视图绑定的解决方案吗?具体来说,我希望找到可以让我做的事情,例如:
Site.Title
期间设置全局CurrentURL
Render
步骤中,只需提供特定于http.Handler
的变量,然后将其组合并提供给模板即可。现有的示例应用程序将是这样的(我将unrolled/render
用于布局继承,但这是可替换的):
package main
import (
"log"
"net"
"net/http"
"os"
"strings"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/unrolled/render"
)
type HelloBinding struct {
Name string
}
func helloHandler(render *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_ = render.HTML(w, http.StatusOK, "hello", &HelloBinding{
Name: "World!",
})
}
}
func main() {
port, ok := os.LookupEnv("PORT")
if !ok {
port = "8080"
}
render := render.New(render.Options{
Directory: "templates",
Layout: "layout",
Extensions: []string{".html"},
IsDevelopment: true,
})
r := chi.NewMux()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
r.Get("/", helloHandler(render))
httpServer := &http.Server{
Addr: net.JoinHostPort("", port),
Handler: r,
}
log.Printf("http server listening at %s\n", httpServer.Addr)
if err := httpServer.ListenAndServe(); err != nil {
log.Panic(err)
}
}
<html>
<head>
<title></title>
</head>
<body>
{{ yield }}
</body>
</html>
和一个共享视图
Hello, {{ .Name }}
在理想的解决方案中,可能会发生以下情况:
警告:伪代码
package main
import (
"log"
"net"
"net/http"
"os"
"strings"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/unrolled/render"
)
type GlobalBinding struct {
Title string
}
type RequestBinding struct {
CurrentURL string
}
type HelloBinding struct {
Name string
}
func helloHandler(render *render.Render) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
_ = render.HTML(w, http.StatusOK, "hello", &HelloBinding{
Name: "World!",
})
}
}
func main() {
port, ok := os.LookupEnv("PORT")
if !ok {
port = "8080"
}
render := render.New(render.Options{
Directory: "templates",
Layout: "layout",
Extensions: []string{".html"},
IsDevelopment: true,
})
// Binds data to be used
render.Bind(GlobalBindings{
Title: "My Site",
})
r := chi.NewMux()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
// Binds data for the request context only
r.Use(func(next http.Handler) http.Handler {
return func(w http.ResponseWriter, r *http.Request) {
render.BindContext(r.Context, RequestBinding{
CurrentURL: r.URL.String(),
})
next(w, r)
}
})
r.Get("/", helloHandler(render))
httpServer := &http.Server{
Addr: net.JoinHostPort("", port),
Handler: r,
}
log.Printf("http server listening at %s\n", httpServer.Addr)
if err := httpServer.ListenAndServe(); err != nil {
log.Panic(err)
}
}
允许我将布局更改为:
<html>
<head>
<title>{{ .Global.Title }}</title>
</head>
<body>
{{ .CurrentURL }}
{{ yield }}
</body>
</html>
然后事情就被合并和绑定了,没有一个处理程序的考虑。
希望你们有一些解决方案!我已经为此苦苦挣扎了一段时间。
答案 0 :(得分:-1)
不在html/template
中,但请考虑使用快速模板
https://github.com/valyala/quicktemplate
它是围绕常规代码设计的,因此您的渲染器只是可以接受任意参数(和接口)的函数。您可以导入包并调用常规函数并访问全局变量。
与内置的模板引擎相比,它使用起来舒适得多,而且您可以进行静态类型检查。唯一的缺点是您需要在编辑后重建/重新启动以反映更改。