假设我有一个页面,它有一个页眉和一个正文。标题中是链接,单击正文会发生变化,但标题仍然存在。
使用 html/template
库构建它很容易,但如果我只是发回一个全新的页面(每次都从数据库中获取标题中的信息),也显得很愚蠢。我猜如何根据 url
切换正文模板。
这是我的:
`
{{template "GlobalNav"}}
{{template "GroupHeader" .Header }}
{{ if eq .Active "" }}
{{ template "GroupBody" .Body }}
{{ else if eq .Active "papers" }}
{{ template "GroupPapers" .Body }}
{{ else if eq .Active "projects" }}
{{ template "GroupProjects" .Body }}
{{ end }}`
Server Side:
`http.HandleFunc("/g/", Groups)
http.HandleFunc("/g/papers", GroupsPapers)
http.HandleFunc("/g/projects", GroupsProjects)
func Groups() {
header := fromDBHeader(id)
body := fromDBMain(id)
render Home template ...
}
func GroupsPapers() {
header := fromDBHeader(id)
body := fromDBPapers(id)
render Paper template ...
}
func GroupsProjects() {
header := fromDBHeader(id)
body := fromDBProjects(id)
render Project template ...
}
`
是时候来点 JS 了吗?
最佳答案
尝试这种方式将 html 文件放入 html 文件夹,向其中添加 html 和 js 文件。
func webServer() {
http.Handle(
"/",
http.StripPrefix(
"/",
http.FileServer(http.Dir("html")),
),
)
http.ListenAndServe(":9000", nil)
并在 http://localhost:9000/ 下浏览
关于go - 与 golang 模板的最小差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39824698/