las*_*owh 46 google-app-engine go
人们如何在基于Go的AppEngine应用程序中处理模板的使用?
具体来说,我正在寻找一个提供以下内容的项目结构:
潜在的障碍是:
请注意,我不是在寻找使用模板包的教程/示例.这更像是一个应用程序结构问题.话虽这么说,如果你有解决上述问题的代码,我很乐意看到它.提前致谢.
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)
这种方法非常令人兴奋,因为它使得应用程序/程序包的共享变得微不足道.如果我编写一个处理身份验证的包,该包具有/auth
url的所有权.然后,任何将包添加到其产品根目录的开发人员都可以立即拥有所有功能.他们所要做的就是创建一个基本模板(templates/base.html
)并引导他们的用户/auth
.
归档时间: |
|
查看次数: |
9763 次 |
最近记录: |