andGo模板中的函数不是短路求值的(不同于
&&Go中的运算符),它的所有参数总是被求值的。从
text/template软件包文档中引用:
and Returns the boolean AND of its arguments by returning the first empty argument or the last argument, that is, "and x y" behaves as "if x then y else x". All the arguments are evaluated.
这意味着
{{if}}您的操作:{{ if and ($.MyStruct.MyField) (eq $.MyStruct.MyField.Value .)}}即使条件将被评估为
falseif
$.MyStruct.MyField是
nil,但
eq $.MyStruct.MyField.Value.也将被评估并导致您得到错误。
相反,您可以嵌入多个
{{if}}操作,如下所示:{{if $.MyStruct.MyField}} {{if eq $.MyStruct.MyField.Value .}}selected="selected"{{end}}{{end}}您也可以使用该
{{with}}动作,但这也可以设置点,因此必须小心:<select name="y"> {{range $idx, $e := .SomeSlice}} <option value="{{.}}" {{with $.MyStruct.MyField}} {{if eq .Value $e}}selected="selected"{{end}}{{end}}>{{.}}</option> {{end}}</select>注意:
您在谈论问题中的
nil值,但
sql.NullXX类型是不能为的结构
nil。在这种情况下,您必须检查其
Valid字段以判断其
Value()方法
nil在调用时是否将返回非值。它可能看起来像这样:
{{if $.MyStruct.MyField.Valid}} {{if eq $.MyStruct.MyField.Value .}}selected="selected"{{end}}{{end}}


