Go语言Web: 模板
如何使用模板轮打一个TODO列表的内容到html页面。
Iris支持5种模板引擎。
这5个模板引擎都有相同的接口,像布局,模板方法等等
标准html, 在 github.com/kataras/go-template/tree/master/html
他的解析器是 golang.org/pkg/html/template/.
Django, 在 ongithub.com/kataras/go-template/tree/master/django
他的解析器是 github.com/flosch/pongo2
Pug(Jade), 在 github.com/kataras/go-template/tree/master/pug
他的解析器是 github.com/Joker/jade
Handlebars, 在 github.com/kataras/go-template/tree/master/handlebars
他的解析器是 github.com/aymerick/raymond
Amber, 在github.com/kataras/go-template/tree/master/amber
他的解析器是 github.com/eknkc/amber
adaptors/view包是视图引擎。
标准html | view.HTML(…)
django | view.Django(…)
pug(jade) | view.Pug(…)
handlebars | view.Handlebars(…)
amber | view.Amber(…)
// todos.go
package mainimport (
"gopkg.in/kataras/iris.v6" "gopkg.in/kataras/iris.v6/adaptors/httprouter" "gopkg.in/kataras/iris.v6/adaptors/view"
)
// Todo结构体
type Todo struct {Task string Done bool
}
func main() {
// 设置选项 app := iris.New\(iris.Configuration{Gzip: false, Charset: "UTF-8"}\) // 配置日志记录器,他会把错误输出到os.Stdout app.Adapt(iris.DevLogger()) // 配置路由器httprouter (所有范例都会使用httprouter路由器) app.Adapt(httprouter.New()) // 解析所有在`./mytemplates`目录里面以`.html`结尾的文件 app.Adapt(view.HTML("./mytemplates", ".html")) todos := []Todo{ {"Learn Go", true}, {"Read GopherBOOk", true}, {"Create a web app in Go", false}, } app.Get("/", func(ctx *iris.Context) { ctx.Render("todos.html", struct{ Todos []Todo }{todos}) }) app.Listen(":8080")
}
<!-- mytemplates/todos.html -->
<h1>Todos</h1>
<ul>
{{range .Todos}}
{{if .Done}}
<li><s>{{.Task}}</s></li>
{{else}}
<li>{{.Task}}</li>
{{end}}
{{end}}
</ul>
$ go run todos.go
Todos
Learn GoRead Go Web Examples- Create a web app in Go