猿问
回到首页
个人中心
反馈问题
注册登录
下载APP
首页
课程
实战
体系课
手记
专栏
慕课教程
如何将变量和字符串与 go 模板连接起来
我需要将作用域变量和字符串与 go 模板连接起来,如下所示:
{{ $url := .Release.Namespace + ".myurl.com" }}
我该怎么做?
月关宝盒
浏览 187
回答 2
2回答
白衣非少年
我相信你来自Helm世界,因为并且可能不想要围棋部分。.Release.Namespace对于掌舵人:Helm 处理您的 YAML 后,其中的所有内容都将被删除。若要实现局部范围的变量,可以使用两个值。{{}}{{}}第一个是 .在 Helm 处理您的 YAML 后,它不会生成任何内容,但它会将局部变量分配给 的值和常量。{{ $url := print .Release.Namespace ".myurl.com" }}$url.Release.Namespace.myurl.com接下来是 ,这将允许您使用存储在变量中的值。{{ $url }}$url将其组合在一起将产生的价值。{{ $url := print .Release.Namespace ".myurl.com" }}{{ $url }}subdomain.myurl.com.Release.Namespacesubdomain对于 Go 开发人员:package mainimport ( "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()) }}
0
0
0
茅侃侃
要简单地连接模板中的值,可以使用内置函数。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如果您的值不是s,它当然有效,因为它是fmt的别名。冲刺():stringprintparams := map[string]interface{}{ "Something": 23,}这个输出(在Go Playground上尝试):Result: 23.myurl.com
0
0
0
打开App,查看更多内容
随时随地看视频
慕课网APP
相关分类
Go
继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续