Golang 模板从字符串数组生成值错误

Golang template generate values from array of strings error

我正在使用需要生成以下内容的 Golang 项目

app1 && app2 && app3

我的模板如下所示

{{- range ExeApp .}} {{ .Command }} {{- end}}

我的代码看起来像下面的命令,它是字符串数组

type App struct {
   Data    string
   Command []string
}

//This is the function
func ExeApp(m models) []App {

   switch m.Type {
   case “apps":
      return []App{
         {"# running apps",
            []string{“app1", “app2", “app3"}},
      }

…

目前生成的像

[app1 app2 app3]

我需要它

app1 && app2 && app3 ,

我尝试通过在 .Command 之前添加 && 来使用模板,但这没有帮助,此外我不知道如何删除应用程序前后的数组 [],不知道我是什么我在这里做错了吗?

我试过以下方法

{{- range .ExeApp}} {{range .Command }} && {{.}} {{end}} {{- end}}

但现在我正在转储 error: unexpected EOF or function "Command" not defined

而 运行 模板

要生成的代码是:

funcMap := template.FuncMap{
    "ExeApp": ExeApp,
}
t, err := template.New("file.txt").Funcs(funcMap).ParseFiles(container)

如果我使用第一个结构(没有字符串数组的相同结构,当然还要调整对象的代码),一切都按预期工作

也试试这个 {{-range .ExeApp}} {{range .Command}} {{.}} {{end}} {{end}}

现在出现错误

executing "file.txt" at <.ExeApp>: can't evaluate field ExeApp in type *models

为什么 :(

在你的最后一个例子中,你有两个范围,只有一个末端(在你编辑之前!)

现在问题已解决,您确定点和命令之间没有 space 吗?尝试在 play.golang.org 上举一个例子,因为错误与您所显示的不匹配 - 来自 funcmap 的函数没有点前缀。

然后为了避免尾随 && 你需要使用带有索引的范围变体,将 && 放在前面,并且只有在索引 > 0

时才打印

我想你想要这样的东西:

https://play.golang.org/p/O8rpum8LtZr

// Define a template.
const tmpl = `
{{ range . -}}
{{range $i,$a := .Command}}{{if gt $i 0 }} && {{end}}{{.}}{{end}}
{{end}}
`

// Prepare some data
type App struct {
    Data    string
    Command []string
}
data := []App{App{"test data", []string{"app1", "app2", "app3"}}}

// Create a new template and parse into it.
t := template.Must(template.New("tmpl").Parse(tmpl))

// Execute the template with data
err := t.Execute(os.Stdout, data)
if err != nil {
    log.Println("executing template:", err)
}

在继续之前阅读 docs for text/template,以消除一些误解 - funcs don't take ., 你可能根本不需要 func,不要用它们来使用上下文传递数据(在我的示例中为数据)。

也许还要考虑在此示例中是否要使用 text/template - 如果您正在构建的字符串是命令行参数,您可能希望查看 os/exec 包的示例反而。

如果要使用从函数返回的数据,请使用 {{ range ExeApp }}(注意没有点)。您的示例引入了几个错误!如果您必须对数据使用 funcmap,请按以下方式操作:

https://play.golang.org/p/euWxctWRbp_L

不过请阅读文档,funcs 不使用点前缀(这很重要),而且 funcmaps 用于助手,而不是数据,你正在存储如果你依赖 funcmaps 获取数据,你自己就会遇到问题,因为你会更难分辨数据的来源,更难调试处理程序等。