如何使用 go 模板连接变量和字符串

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

我需要用 go 模板连接一个作用域变量和一个字符串,就像这样:

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

我该怎么做?

要简单地连接模板中的值,您可以使用内置 print 函数。

看这个例子:

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)
}

输出(在 Go Playground 上尝试):

Result: test.myurl.com

如果您的值不是 string,它当然有效,因为 printfmt.Sprint():

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

此输出(在 Go Playground 上尝试):

Result: 23.myurl.com

由于 .Release.Namespace,我相信您来自 Helm 世界,并且可能不想要其中的 Go 部分。

对于 Helm 人员:

Helm 处理您的 YAML 后,{{}} 内的所有内容都将被删除。要实现局部范围的变量,您可以使用两个 {{}} 值。

第一个是{{ $url := print .Release.Namespace ".myurl.com" }}。在 Helm 处理你的 YAML 后它不会产生任何东西,但它会将局部变量 $url 分配给 .Release.Namespace 的值和常量 .myurl.com.

下一个是 {{ $url }},这将允许您使用存储在 $url 变量中的值。

如果 .Release.Namespace 的值是 subdomain.

,则将其放在一起 {{ $url := print .Release.Namespace ".myurl.com" }}{{ $url }} 将产生 subdomain.myurl.com

对于 Go 开发者:

Playground link

package main

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

const (
    // exampleTemplate is a template for a Whosebug 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())
    }
}