How to concatenate a variable and a string with the go templates

Viewed 4679

I need to concatenate a scoped variable and a string with go templates, something like that:

{{ $url := .Release.Namespace + ".myurl.com" }}

How can I do that?

2 Answers

I believe you're coming from the Helm world due to .Release.Namespace and may not want the Go portion of this.

For Helm people:

Everything inside of the {{}} will be removed after Helm processes your YAML. To achieve a locally scoped variable, you can use two {{}} values.

The first is {{ $url := print .Release.Namespace ".myurl.com" }}. It won't produce anything after Helm processes your YAML, but it will assign the local variable $url to the value of .Release.Namespace and the constant .myurl.com.

The next is {{ $url }}, which will allow you to use the value stored in the $url variable.

Bringing it together {{ $url := print .Release.Namespace ".myurl.com" }}{{ $url }} will produce subdomain.myurl.com should the value of .Release.Namespace be subdomain.

For Go developers:

Playground link

package main

import (
    "log"
    "os"
    "text/template"
)

const (
    // exampleTemplate is a template for a StackOverflow example.
    exampleTemplate = `{{ $url := print .Release.Namespace ".myurl.com" }}{{ $url }}`
)

// templateData is the data structure to pass to the template.
type templateData struct {
    Release Release
}

// Release is a fake Go data structure for this example.
type Release struct {
    Namespace string
}

func main() {
    // Create the template.
    tmpl := template.Must(template.New("example").Parse(exampleTemplate))

    // Create the data to put into the template.
    data := templateData{Release: Release{Namespace: "subdomain"}}

    // Execute the template.
    if err := tmpl.Execute(os.Stdout, data); err != nil {
        log.Fatalf("Failed to execute template.\nError: %s", err.Error())
    }
}

To simply concatenate values in templates, you may use the builtin print function.

See this example:

const src = `{{ $url := print .Something ".myurl.com" }}Result: {{ $url }}`
t := template.Must(template.New("").Parse(src))

params := map[string]interface{}{
    "Something": "test",
}

if err := t.Execute(os.Stdout, params); err != nil {
    panic(err)
}

Output (try it on the Go Playground):

Result: test.myurl.com

It of course works if your values are not strings because print is an alias for fmt.Sprint():

params := map[string]interface{}{
    "Something": 23,
}

This outputs (try it on the Go Playground):

Result: 23.myurl.com
Related