go - 与 golang 模板的最小差异?

标签 go go-templates

假设我有一个页面,它有一个页眉和一个正文。标题中是链接,单击正文会发生变化,但标题仍然存在。 使用 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/

相关文章:

Golang SMTP 发送空邮件

go - 转到模板: how to pass the variable returned from a function to next command in pipeline

go - 在范围循环中获取 {{.Host}} - Caddy 服务器浏览模板

go - 全局模板数据

html - 如何在go模板中传入map "created on the way"

转到模板 : can't evaluate field X in type Y (X not part of Y but stuck in a {{range}} loop)

go - 如果写入从不在设计上相互竞争,那么使用 sync.RWMutex 的读取锁进行写入并使用其写入锁进行读取是否安全?

pointers - 传递给nil的方法时,Golang指针未更新

go - golang中常量值自动类型如何工作?

multithreading - goroutines(以及运行它们的操作系统线程)在被 IO 绑定(bind)操作阻塞时如何表现?