Make sure path in Go template always ends with slash

2/14/2020

I am writing a Helm chart for a bunch of deployments. I am supplying a value which can be:

my_value: "/opt/my-path"or my_value: "/opt/my-path/"

Now I would want to make sure that there is always a single / at the end of the path.

How do I do this using Go templates?

-- Hedge
go-templates
kubernetes-helm
sprig-template-functions

1 Answer

2/15/2020

You can trim the suffix / with trimSuffix function, docs here http://masterminds.github.io/sprig/strings.html, and to add / manually at the end. So regardless the original value you will always get a / at the end. example

values.yaml:

path_with_slash: "/my/path/"
path_without_slash: "/my/path"

inside a template file:

{{ $path_with_slash := trimSuffix "/" .Values.path_with_slash }}
{{ $path_without_slash := trimSuffix "/" .Values.path_without_slash }}
path_with_slash: "{{ $path_with_slash }}/"
path_without_slash: "{{ $path_without_slash }}/"

rendered file:

path_with_slash: "/my/path/"
path_without_slash: "/my/path/"
-- Yuri G.
Source: StackOverflow