<p>I need to reduce my 'if else code' in my helm chart template<br />
How can I do that ?.</p>
<pre><code>  {{- if .Values.global }}
    {{- if .Values.global.namespace }}
      namespace: {{ .Values.global.namespace }}
    {{- else }}
      namespace: {{ .Values.namespace }}
    {{- end }}
  {{- else }}
    namespace: {{ .Values.namespace }}
  {{- end}}
  name: {{.Values.name}}
</code></pre>

karlos
<p>&quot;If <code>x</code> is truthy, then use its value, otherwise use <code>y</code>&quot; is what the Helm (Sprig) <a href="https://docs.helm.sh/docs/chart_template_guide/function_list/#default" rel="nofollow noreferrer"><code>default</code></a> function does.  You could replace the inner conditional with</p>
<pre class="lang-yaml prettyprint-override"><code>namespace: {{ .Values.global.namespace | default .Values.namespace }}
</code></pre>
<p>The outer conditional is trickier.  The problem you're trying to work around here is, if <code>.Values.global</code> isn't defined, it will evaluate to <code>nil</code>, and then <code>.Values.global.namespace</code> is an error.  The usual approach I use here is to again use <code>default</code> to get an empty dictionary if it isn't defined, at which point you can successfully do a lookup.</p>
<p>So you should be able to replace the entire block with</p>
<pre class="lang-yaml prettyprint-override"><code>{{- $global := .Values.global | default dict }}
namespace: {{ $global.namespace | default .Values.namespace }}
</code></pre>
