Maison > développement back-end > Golang > le corps du texte

Go 模板和多行字符串缩进

WBOY
Libérer: 2024-02-09 22:09:14
avant
446 人浏览过

Go 模板和多行字符串缩进

php小编子墨为您介绍Go语言中的模板和多行字符串缩进。在Go语言中,模板是一种方便生成文本输出的工具,它可以将变量插入到指定的模板中,并生成最终的输出结果。同时,多行字符串缩进是一种使代码更易读的技巧,它可以使代码在多行展示时保持一致的缩进风格,提高代码的可读性和维护性。在本文中,我们将详细介绍Go语言中模板的使用方法和多行字符串缩进的技巧,帮助您更好地应用于实际开发中。

问题内容

因此,我尝试使用 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)
}
Copier après la connexion

游乐场:https://goplay.space/#2ek7_elztwa

我想在这里看到的输出显然是

routes:
  foo
  bar
Copier après la connexion

而不是

routes:
  foo
bar
Copier après la connexion

是否有一些神奇的前缀可以避免这种情况?

解决方法

我能够使用以下代码来满足您的要求。我使用了包小枝。它为我们提供了可以轻松实现您目标的功能。代码如下:

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)
}
Copier après la connexion

我使用 funcs 方法将函数传递到模板引擎中。这些函数是从对 sprig.funcmap() 的调用中返回的。

请注意,您必须在 parse 之前调用此函数,否则会出现混乱。

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

可以在此处找到可用功能的完整列表。
如果这解决了您的问题,请告诉我,谢谢!

以上是Go 模板和多行字符串缩进的详细内容。更多信息请关注PHP中文网其他相关文章!

Étiquettes associées:
source:stackoverflow.com
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!