【问题标题】:How to access struct fields in a template如何访问模板中的结构字段
【发布时间】:2018-03-12 07:47:15
【问题描述】:

我想在范围循环内比较两个字符串类型的变量,如下所示:

<select name="category" id="category">            
    {{range $c := .cats}}
      <option value="{{$c.Title}}"  {{ if eq $c.Title .category}}active{{end}}>{{$c.Title}}</option>                                       
    {{end}}    
</select>

$c.Titlecategory 都是由控制器调度的字符串。

但是,当下拉菜单出现在呈现的模板中时,我得到:

无法评估 model.category 类型中的字段类别

$c 属于结构类型类别:

type Category struct {
    ID        int       `db:"id"`
    Title     string    `db:"title"`
    Slug      string    `db:"slug"`
    CreatedAt time.Time `db:"created_at"`
}

当我在上面的代码中直接输入category而不是.category的字符串值时,没有问题。
我正在使用gowebapp MVC 框架,如果它确实重要的话。

我该如何解决这个问题?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    您要比较的 .category 值不是您的 model 的一部分,但模板引擎会尝试将 .category 解析为 category 是您的 model 值的字段或方法。

    这是因为{{range}} 操作将点. 设置为每次迭代中的连续元素。

    要引用顶级category,您可以像这样使用$ 符号:

    <select name="category" id="category">            
        {{range $c := .cats}}
          <option value="{{$c.Title}}"  {{ if eq $c.Title $.category}}active{{end}}>{{$c.Title}}</option>                                       
        {{end}}    
    </select>
    

    查看这个可运行的示例:

    func main() {
        t := template.Must(template.New("").Parse(src))
        params := map[string]interface{}{
            "category": "Cars",
            "cats": []struct{ Title string }{
                {"Animals"}, {"Cars"}, {"Houses"},
            },
        }
        if err := t.Execute(os.Stdout, params); err != nil {
            panic(err)
        }
    }
    
    const src = `<select name="category" id="category">            
        {{range $c := .cats}}
          <option value="{{$c.Title}}"  {{ if eq $c.Title $.category}}active{{end}}>{{$c.Title}}</option>                                       
        {{end}}    
    </select>`
    

    输出(在Go Playground上试试):

    <select name="category" id="category">            
    
          <option value="Animals"  >Animals</option>
    
          <option value="Cars"  active>Cars</option>
    
          <option value="Houses"  >Houses</option>
    
    </select>
    

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2023-03-19
      • 2020-07-08
      • 1970-01-01
      • 2010-11-03
      • 2020-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多