Dar*_*key 4 templates json go go-templates
我正在寻找一种将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 )
}
Run Code Online (Sandbox Code Playgroud)
我试过json.Unmarshal,但似乎想要一个类型.最重要的是,在实际程序中,json和模板都来自数据库,并且在运行时完全可以更改(并且有很多不同的),因此我无法对go程序本身中的任何结构进行编码.显然,我希望能够制作如下数据:
{ "something" : { "a" : "whatever" }}
Run Code Online (Sandbox Code Playgroud)
然后是一个模板
<html><body>
the value is {{ .something.a }}
</body></html>
Run Code Online (Sandbox Code Playgroud)
这可以通过go http.template库实现,还是需要转到Node(或找到另一个模板库?)
您可以使用json.Unmarshal()
将JSON文本解组为Go值.
您只需使用Go类型interface{}
来表示任意JSON值.通常,如果它是一个struct,map[string]interface{}
则使用它并且如果你需要在Go代码中引用存储在它中的值更有用(例如,这不能代表一个数组).
template.Execute()
并将template.ExecuteTemplate()
模板的数据/参数作为interface{}
您可以在Go中传递任何内容的类型值.而template
引擎使用反射(reflect
包),"发现"它的运行时类型,并根据您在模板的动作(可以指定结构或键的字段映射,甚至方法名)提供选择的导航.
除此之外,一切都按预期工作.看这个例子:
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]}`
Run Code Online (Sandbox Code Playgroud)
输出(在Go Playground上试试):
<html><body>
Value of a: valueofa
Something else: [1234 5678]
</body></html>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8140 次 |
最近记录: |