英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论