为了账号安全,请及时绑定邮箱和手机立即绑定

如何将变量和字符串与 go 模板连接起来

如何将变量和字符串与 go 模板连接起来

Go
月关宝盒 2022-08-01 09:37:19
我需要将作用域变量和字符串与 go 模板连接起来,如下所示:{{ $url := .Release.Namespace + ".myurl.com" }}我该怎么做?
查看完整描述

2 回答

?
白衣非少年

TA贡献1155条经验 获得超0个赞

我相信你来自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 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())

    }

}


查看完整回答
反对 回复 2022-08-01
?
茅侃侃

TA贡献1842条经验 获得超21个赞

要简单地连接模板中的值,可以使用内置函数。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的别名。冲刺():stringprint


params := map[string]interface{}{

    "Something": 23,

}

这个输出(在Go Playground上尝试):


Result: 23.myurl.com


查看完整回答
反对 回复 2022-08-01
  • 2 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号