Go 将两个if条件合并为一个

Go 将两个if条件合并为一个,go,kubernetes-helm,go-templates,sprig-template-functions,Go,Kubernetes Helm,Go Templates,Sprig Template Functions,下面的工作 {{- if hasKey (index $envAll.Values.policy) "type" }} {{- if has "two-wheeler" (index $envAll.Values.policy "type") }} <code goes here> {{- end }} {{- end }} {-if hasKey(index$envAll.Values.policy)“type”} {{-if有“两轮”(索引$envAll.Values.pol

下面的工作

{{- if hasKey (index $envAll.Values.policy) "type" }} 
{{- if has "two-wheeler" (index $envAll.Values.policy "type") }}
<code goes here>
{{- end }}
{{- end }}
{-if hasKey(index$envAll.Values.policy)“type”}
{{-if有“两轮”(索引$envAll.Values.policy“type”)}

{{-end}
{{-end}
当以下操作失败时,“运行时错误:无效内存地址或零指针取消引用”

{-if和(hasKey(index$envAll.Values.policy)“type”)(有“two-wheeler”(index$envAll.Values.policy“type”)}

{{-end}
在$envAll.Values.policy下没有按名称“type”声明的列表

在Go中,如果右操作数按条件求值,为什么最后一个条件在第二个代码段中求值?我如何解决它

编辑(因为它标记为重复): 不幸的是,我不能像在另一篇文章中提到的那样使用嵌入式{{if}}

我简化了上面的问题。我必须做到这一点

{{if or (and (condition A) (condition B)) (condition C)) }}
    <code goes here>
{{ end }}
{{if or(和(条件A)(条件B))(条件C))}

{{end}

由于Go模板中的
函数未进行短路计算(与Go中的
&&
运算符不同),因此使用
函数时会出现错误,其所有参数都将始终进行计算。请在此处阅读更多信息:

因此,您必须使用嵌入的
{{if}}
操作,因此只有当第一个参数也是true时,才会计算第二个参数

您编辑了问题,并指出您的实际问题是:

{{if or (and (condition A) (condition B)) (condition C)) }}
    <code goes here>
{{ end }}
{{if or(和(条件A)(条件B))(条件C))}

{{end}
以下是仅在模板中执行此操作的方法:

{{ $result := false }}
{{ if (conddition A )}}
    {{ if (condition B) }}
        {{ $result = true }}
    {{ end }}
{{ end }}
{{ if or $result (condition C) }}
    <code goes here>
{{ end }}
{{$result:=false}
{{if(条件A)}
{{if(条件B)}
{{$result=true}
{{end}
{{end}
{{if或$result(条件C)}

{{end}
另一个选项是将该逻辑的结果作为参数传递给模板


如果您在调用模板之前不能或不知道结果,另一个选项是注册一个自定义函数,并从模板中调用此自定义函数,您可以在Go代码中执行短路求值。例如,请参见。

Go模板中的
函数未进行短路计算(与Go中的
&&
运算符不同),其所有参数始终进行计算。所以使用2
{{if}}
是正确的方法。@icza,谢谢。我编辑了我的问题。如果你相信我的编辑,你能删除重复标记吗?不管逻辑是否是其他的:模板中的
都会计算所有参数,所以答案仍然是一样的。我正在寻找解决我问题的方法。另一个答案不能解决我的问题。只要它被标记为重复,它就不会引起其他人的注意。仅供参考,只需在变量result:$result中添加$。否则,它将以“函数”结果“未定义”失败@Hem是的,您是对的。我没有试过这个例子,只是凭记忆写的。固定的。谢谢
{{ $result := false }}
{{ if (conddition A )}}
    {{ if (condition B) }}
        {{ $result = true }}
    {{ end }}
{{ end }}
{{ if or $result (condition C) }}
    <code goes here>
{{ end }}