Go模板和多行字符串缩进

huangapple go评论85阅读模式
英文:

Go templates and multiline string indentation

问题

我正在尝试使用text/template包生成一个YAML文件,其中模板值是一个多行字符串。我遇到的问题是模板字符串的缩进与tpl中的模板变量不在同一级别。

这是一个(有些牵强的)例子:

package main

import (
	"os"
	"text/template"
)

func main() {
	tpl := template.Must(template.New("yml").Parse(
		`routes:
  {{ . }}
`))

	value := `foo
bar`
	tpl.Execute(os.Stdout, value)
}

Playground: https://goplay.space/#2eK7_ELZTwA

我希望看到的输出显然是:

routes:
  foo
  bar

而不是:

routes:
  foo
bar

有没有一些特殊的前缀可以避免这个问题?

英文:

So I am trying to generate a YAML file by using the text/template package with a template value that is a multiline string. What I am struggling with is the indentation of the template string not being at the same level of the template variable in the tpl.

The (somewhat contrived example) here:

package main

import (
	"os"
	"text/template"
)

func main() {
	tpl := template.Must(template.New("yml").Parse(
		`routes:
  {{ . }}
`))

	value := `foo
bar`
	tpl.Execute(os.Stdout, value)
}

Playground: https://goplay.space/#2eK7_ELZTwA

The output I'd like to see here is obviously

routes:
  foo
  bar

and not

routes:
  foo
  bar

Is there some magic prefix to avoid this?

答案1

得分: 1

我使用以下代码来处理您的要求。我使用了包sprig。它提供了一些功能,使得实现您的目标变得容易。代码如下:

package main

import (
	"os"
	"text/template"

	"github.com/Masterminds/sprig/v3"
)

func main() {
	tpl := template.Must(template.New("yml").Funcs(sprig.FuncMap()).Parse(
		`routes:
{{ . | indent 2 }}
`))

	value := `foo
bar`
	tpl.Execute(os.Stdout, value)
}

我使用了Funcs方法将函数传递给模板引擎。这些函数是从调用sprig.FuncMap()返回的。

请注意,在Parse之前必须调用此函数,否则会引发错误。

然后,我添加了注释| indent 2,以使我们的行缩进两个字符。如果您运行此代码,您将得到所需的输出。

可以在这里找到可用函数的完整列表。

如果这解决了您的问题,请告诉我,谢谢!

英文:

I was able to handle your requirements with the following code. I used the package sprig. It provides us with features that make it easy to achieve your goal. The code is as follows:

package main

import (
	"os"
	"text/template"

	"github.com/Masterminds/sprig/v3"
)

func main() {
	tpl := template.Must(template.New("yml").Funcs(sprig.FuncMap()).Parse(
		`routes:
{{ . | indent 2 }}
`))

	value := `foo
bar`
	tpl.Execute(os.Stdout, value)
}

I used the method Funcs to pass the functions into the template engine. These functions are returned from the invocation to sprig.FuncMap().
> Please note that you must invoke this function before the Parse otherwise it panics.

Then, I added the annotation | indent 2 to indent our lines by two characters. If you run the code, you'll get the desired output.

A complete list of the available function can be found here.
Let me know if this solves your issue, thanks!

huangapple
  • 本文由 发表于 2023年6月21日 17:02:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76521609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定