将两个 if 条件合并为一个

Hem*_*Hem 5 go go-templates kubernetes-helm sprig-template-functions

下面的作品

{{- if hasKey (index $envAll.Values.policy) "type" }} 
{{- if has "two-wheeler" (index $envAll.Values.policy "type") }}
<code goes here>
{{- end }}
{{- end }}
Run Code Online (Sandbox Code Playgroud)

而下面的失败并显示“运行时错误:无效的内存地址或零指针取消引用”

{{- if and (hasKey (index $envAll.Values.policy) "type") (has "two-wheeler" (index $envAll.Values.policy "type")) }}
<code goes here>
{{- end}}
Run Code Online (Sandbox Code Playgroud)

$envAll.Values.policy 下没有声明名称为“type”的列表。

在 Go 中,如果有条件地计算正确的操作数,为什么最后一个条件在第二个代码片段中被计算?我该如何解决?

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

我在上面简化了我的问题。我实际上必须实现这个目标......

{{if or (and (condition A) (condition B)) (condition C)) }}
    <code goes here>
{{ end }}
Run Code Online (Sandbox Code Playgroud)

icz*_*cza 7

更新:以下答案早于 Go 1.18,其中参数评估andor模板函数更改为如果结果已知则提前停止。答案仅对之前的 Go 版本有效。


使用该函数时会出现错误and,因为andGo 模板中的函数不是短路计算的(与&&Go 中的运算符不同),它的所有参数始终都会计算。在这里阅读更多相关信息:Golang 模板和有效字段测试

因此,您必须使用嵌入式{{if}}操作,因此仅当第一个参数也为 true 时才评估第二个参数。

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

{{if or (and (condition A) (condition B)) (condition C)) }}
    <code goes here>
{{ end }}
Run Code Online (Sandbox Code Playgroud)

这是仅在模板中执行此操作的方法:

{{ $result := false }}
{{ if (conddition A )}}
    {{ if (condition B) }}
        {{ $result = true }}
    {{ end }}
{{ end }}
{{ if or $result (condition C) }}
    <code goes here>
{{ end }}
Run Code Online (Sandbox Code Playgroud)

另一种选择是将该逻辑的结果作为参数传递给模板。

如果在调用模板之前你不能或不知道结果,还有一个选择是注册一个自定义函数,并从模板中调用这个自定义函数,你可以在 Go 代码中进行短路评估。有关示例,请参阅如何计算 html/template 中的内容