Golang直接在模板中使用json
我正在寻找一种将json数据直接绑定到模板中(在golang中没有任何结构表示)的方法,我的目标很短。本质上,我希望模板文档和json都是任意数据,而我的handleFunc本质上是:Golang直接在模板中使用json,json,templates,go,go-templates,Json,Templates,Go,Go Templates,我正在寻找一种将json数据直接绑定到模板中(在golang中没有任何结构表示)的方法,我的目标很短。本质上,我希望模板文档和json都是任意数据,而我的handleFunc本质上是: func handler(writer http.ResponseWriter, request *http.Request) { t, _ := template.ParseFiles( "someTemplate.html" ) rawJson, _ := ioutil.ReadFile( "
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>
值为{{.something.a}
go http.template库是否可以实现这一点,或者我是否需要转到节点(或查找另一个模板库?您可以使用它将JSON文本解组为go值
您可以简单地使用Go类型接口{}
来表示任意JSON值。通常,如果它是一个结构,则使用map[string]接口{}
,如果您也需要在Go代码中引用存储在其中的值,则更有用(但这不能表示例如数组)
并将模板的数据/参数作为interface{}
类型的值,您可以在Go中向其传递任何内容。而模板
引擎使用反射(包)来“发现”其运行时类型,并根据模板操作中提供的选择器(可能指定映射中的结构或键字段,甚至方法名称)在其中导航
除此之外,一切正常。请参见此示例:
func main() {
t := template.Must(template.New("").Parse(templ))
m := map[string]interface{}{}
if err := json.Unmarshal([]byte(jsondata), &m); err != nil {
panic(err)
}
if err := t.Execute(os.Stdout, m); err != nil {
panic(err)
}
}
const templ = `<html><body>
Value of a: {{.something.a}}
Something else: {{.somethingElse}}
</body></html>`
const jsondata = `{"something":{"a":"valueofa"}, "somethingElse": [1234, 5678]}`
func main(){
t:=template.Must(template.New(“”).Parse(templa))
m:=map[string]接口{}{}
如果err:=json.Unmarshal([]字节(jsondata),&m);err!=nil{
恐慌(错误)
}
如果err:=t.Execute(os.Stdout,m);err!=nil{
恐慌(错误)
}
}
常数模板=`
a的值:{{.something.a}
其他的:{{.somethingElse}
`
const jsondata=`{“something”:{“a”:“valueofa”},“somethingElse”:[12345678]}`
输出(在上尝试):
a的值:a的值
还有点别的:[12345678]
<html><body>
Value of a: valueofa
Something else: [1234 5678]
</body></html>