gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:07:22 27 4
gpt4 key购买 nike

我需要使用go模板将范围变量和字符串连接起来,如下所示:

{{ $url := .Release.Namespace + ".myurl.com" }}
我怎样才能做到这一点?

最佳答案

我相信您是因为.Release.Namespace而来自Helm世界,并且可能不想要其中的Go部分。
对于Helm人:
Helm处理您的YAML之后,{{}}内部的所有内容都将被删除。要获得局部范围的变量,可以使用两个{{}}值。
第一个是{{ $url := print .Release.Namespace ".myurl.com" }}。在Helm处理您的YAML之后,它不会产生任何结果,但是它将为$url的值和常量.Release.Namespace分配局部变量.myurl.com
下一个是{{ $url }},它将允许您使用存储在$url变量中的值。
如果{{ $url := print .Release.Namespace ".myurl.com" }}{{ $url }}的值为subdomain.myurl.com,将.Release.Namespace放在一起将产生subdomain
对于Go开发人员:
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())
}
}

关于go - 如何使用go模板连接变量和字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65358727/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com