Skip to content

proposal: text/template: safe navigation with ?. #43608

@thernstig

Description

@thernstig

It would be beautiful if the package text/template (used by e.g. Helm) could support optional chaining. Similar to JavaScript in latest standard ECMAScript 2020. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

It would basically look like this:

spec:
  type: {{ .Values.service?.type | default "ClusterIP" }}

If service is not defined, it would short-circuit to undefined/false and thus default to "ClusterIP".

This could be used in other cases, such as:

spec:
  {{- if .Values.global?.internalIPFamily }}
  ipFamily: {{ .Values.global.internalIPFamily }}
  {{- end }}

It solves a few things in e.g. Helm that uses text/template for templating:

  1. default not working when parent values does not exist in a chain, giving errors, see nil pointer evaluating interface when upper level doesn't exist prevents usage of default function helm/helm#8026.
  2. It would be able to get rid of the, in my opinion, not great best practice for nested or flat values for e.g. Helm (which I assume is applicable to other text/template usages as well), see https://helm.sh/docs/chart_best_practices/values/#flat-or-nested-values. Optional chaining would instead still make the code more readable (one-liner) not caring about value depth. It would also in my opinion make it easier to read YAML files with the nested structure, clearly separating levels, than to use camelCase.

As I know very little about Go and the packge text/template, feel free to add more precise info on how this translates to what needs to be done in text/template.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

Status

Incoming

Relationships

None yet

Development

No branches or pull requests

Issue actions