【问题标题】:Golang use json in template directlyGolang 直接在模板中使用 json
【发布时间】: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


    【解决方案1】:

    您可以使用 json.Unmarshal() 将 JSON 文本解组为 Go 值。

    您可以简单地使用 Go 类型 interface{} 来表示任意 JSON 值。通常如果它是一个结构,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]}`
    

    输出(在Go Playground上试试):

    <html><body>
        Value of a: valueofa
        Something else: [1234 5678]
    </body></html>
    

    【讨论】:

      猜你喜欢
      • 2021-11-13
      • 2015-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-10
      相关资源
      最近更新 更多