栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Golang模板并测试有效字段

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Golang模板并测试有效字段

and
Go模板中的函数不是短路求值的(不同于
&&
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 .)}}

即使条件将被评估为

false
if
$.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}}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452336.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号