【问题标题】:How to access an element of a struct which is inside a struct of slice in gohtml?如何访问gohtml中切片结构内的结构元素?
【发布时间】:2020-04-28 06:25:51
【问题描述】:

我有一个结构 A,结构 C 的切片 B 和其他数据类型。我将它传递给 gohtml 模板。如何在 gohtml 模板中访问 struct C 的元素。

type Str1 struct{
      var_x string
      var_y string
}

type Str2 struct {
      var_a []Str1
      var_b string
}
func main(){

B := make([]Str1], 0)

//code to append values of struct Str1 to Slice object B

str_var := Str2{B,"Good"} 

tpl = template.Must(template.ParseGlob("template/*.gohtml"))

tpl.ExecuteTemplate(w, "example.gohtml", str_var)

}

我的问题是关于遍历底层切片并访问 gohtml 代码中的“var_x & var_y”。在下面的示例中是“A,Apple,B,Ball....”

{[{A Apple} {B Ball} {C Cat} {A Air} {B Bat} {C Coat} {D Dog} {E Ear}] 好}

【问题讨论】:

    标签: go struct slice go-html-template


    【解决方案1】:

    通过以大写 Unicdoe 字符开头的字段名称来导出字段。

    type Str1 struct {
        Var_x string
        Var_y string
    }
    
    type Str2 struct {
        Var_a []Str1
        Var_b string
    }
    

    使用 .运算符来引用点值的字段。

     {{range .Var_a}}{{.Var_x}}: {{.Var_y}}; {{end}}
    

    https://play.golang.org/p/KTlSWy10c4R

    【讨论】:

      猜你喜欢
      • 2021-09-20
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      • 2022-10-23
      • 2019-08-10
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多