2016-01-10 07:29

Go HTML模板中的字段检测

  • it技术
  • 互联网问答
  • IT行业问题
  • 编程语言问答
  • 计算机技术

Is it possible to check if a struct field exists from within a Go HTML template?

For example, given the following template:

{{if .FieldA}}

and structs defined as:

type MyStruct struct{  
    var FieldA string
    var FieldB string
// In this struct FieldA is unavailable
type MyStruct2 struct{  
    var FieldB string

Passing MyStruct into the template will work fine. However, passing MyStruct2 into the template will result in error. While the if statement can check for nil values, it throws an error (killing the template executor) when it encounters a field which doesn't exist in the current struct.

Sometimes a particular field is only going to be available in certain structs, so is there a way to check if the field exists prior to attempting to access it?

I've had no luck with the official documentation and have come to the conclusion that perhaps there is no elegant solution.

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享