【发布时间】:2016-07-18 12:35:08
【问题描述】:
我正在寻找一种将 json 数据直接绑定到模板中的方法(在 golang 中没有任何结构表示)——但我做不到。本质上,我想要的是让模板文档和 json 都成为任意数据——而我的 handleFunc 基本上是:
func handler(writer http.ResponseWriter, request *http.Request) {
t, _ := template.ParseFiles( "someTemplate.html" )
rawJson, _ := ioutil.ReadFile( "someData.json" )
// here's where I need help
somethingTemplateUnderstands := ????( rawJson )
t.Execute( writer, somethingTemplateUnderstands )
}
我试过 json.Unmarshal,但它似乎想要一个类型。主要的是,在实际程序中,json 和模板都来自数据库,并且在运行时完全可以更改,(并且有很多不同的)所以我不能在 go 程序本身中编码任何结构。显然,我希望能够制作如下数据:
{ "something" : { "a" : "whatever" }}
然后是模板
<html><body>
the value is {{ .something.a }}
</body></html>
go http.template 库可以做到这一点,还是我需要转到 Node(或寻找另一个模板库?)
【问题讨论】:
标签: json templates go go-templates