Go,AppEngine:如何为应用程序构建模板

las*_*owh 46 google-app-engine go

人们如何在基于Go的AppEngine应用程序中处理模板的使用?

具体来说,我正在寻找一个提供以下内容的项目结构:

  • 模板和部分模板的分层(目录)结构
  • 允许我在我的模板上使用HTML工具/编辑器(在xxx.go文件中嵌入模板文本会使这很困难)
  • 在开发服务器上自动重新加载模板文本

潜在的障碍是:

  • template.ParseGlob()不会递归遍历.
  • 出于性能原因,建议不要将模板上载为原始文本文件(因为这些文本文件驻留在不同于执行代码的服务器上).

请注意,我不是在寻找使用模板包的教程/示例.这更像是一个应用程序结构问题.话虽这么说,如果你有解决上述问题的代码,我很乐意看到它.提前致谢.

Kyl*_*ley 68

Go最喜欢的功能之一是能够在包内轻松添加处理程序.这极大地简化了编写模块化代码的过程.

例如:

文件结构

|-- app.yaml
|-- app
|   +-- http.go
|-- templates
|   +-- base.html
+-- github.com
    +-- storeski
        +-- appengine
            |-- products
            |   |-- http.go
            |   +-- templates
            |       |-- list.html
            |       +-- detail.html 
            +-- account
                |-- http.go
                +-- templates
                    |-- overview.html
                    +-- notifications.html 
Run Code Online (Sandbox Code Playgroud)

每个包都有一个http.go文件,该文件拥有url前缀的所有权.例如,products下面的包github.com/storeski/appengine/products将拥有以/products.开头的任何入站URL .

使用这种模块化方法,将模板存储在products包中是有益的.如果您希望为站点维护一致的基本模板,则可以建立扩展的约定templates/base.html.

模板/ base.html文件

<!DOCTYPE HTML>
<html>
  <head>
    <title>{{.Store.Title}}</title>
  </head>

  <body>
    <div id="content">
      {{template "content" .}}
    </div>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

github.com/storeski/appengine/products/templates/list.html

{{define "content"}}
  <h1> Products List </h1>
{{end}}
Run Code Online (Sandbox Code Playgroud)

github.com/storeski/appengine/products/http.go

func init() {
  http.HandleFunc("/products", listHandler)
}

var listTmpl = template.Must(template.ParseFiles("templates/base.html",
  "github.com/storeski/appengine/products/templates/list.html"))

func listHandler(w http.ResponseWriter, r *http.Request) {

  tc := make(map[string]interface{})
  tc["Store"] = Store
  tc["Products"] = Products

  if err := listTmpl.Execute(w, tc); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
  }
}
Run Code Online (Sandbox Code Playgroud)

这种方法非常令人兴奋,因为它使得应用程序/程序包的共享变得微不足道.如果我编写一个处理身份验证的包,该包具有/authurl的所有权.然后,任何将包添加到其产品根目录的开发人员都可以立即拥有所有功能.他们所要做的就是创建一个基本模板(templates/base.html)并引导他们的用户/auth.

  • 嗨@PatrickLinskey,你的`app.yaml`文件应该*不包含`templates`目录.App Engine将`app.yaml`文件中列出的目录视为静态资源,但是可以从代码访问`app.yaml`文件中未列出的任何目录.我希望有所帮助. (2认同)