dsaaqdz6223 2018-07-29 14:30
浏览 72
已采纳

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

Im using Golang project which needs to generate the following

app1 && app2 && app3

My template look like following

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

My code looks like following with command which is array of strings

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"}},
      }

…

Currently its generated like

[app1 app2 app3]

And I need it like

app1 && app2 && app3 ,

I try to play with the template by adding && before the .Command which doesn’t help and in addition I don’t know how to remove the array [] before and after the apps, any idea what I’m doing wrong here ?

i've tried with the following

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

But now im getting dump with error: unexpected EOF or function "Command" not defined

while running the template

The code to generate is:

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

in case Im working with the first structure (same structure without the array of strings and of course adapt the code of the object) everything is working as expected

Try also with this {{-range .ExeApp}} {{range .Command}} {{.}} {{end}} {{end}}

Now im getting error

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

why :(

  • 写回答

1条回答 默认 最新

  • dsf487787 2018-07-29 17:37
    关注

    In your final example you have two ranges and only one end (prior to your edit!)

    Now that is fixed, are you sure you don't have a space between the dot and Command? Try putting an example on play.golang.org as the errors don't match what you have shown - funcs from funcmap don't have a dot prefix.

    Then to avoid trailing && you'll need to use the variant of range with an index, put the && before and only print if index > 0

    I think you want something like this:

    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)
    }
    

    Read the docs for text/template before proceeding, to clear up a few misunderstandings - funcs don't take ., you may not need a func at all, don't use them to pass data in use a context for that (data in my example).

    Also perhaps consider in this example whether you want to use text/template at all - if the strings you are building are command line arguments you may well want to look at examples for the os/exec package instead.

    Use {{ range ExeApp }} (note no dot) if you want to use the data returned from a function. Your example introduces several errors! If you must use a funcmap for data, here is how you'd do it:

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

    Please do read the docs though, funcs don't use the dot prefix (that's rather important), and also funcmaps are for helpers, not data, you are storing up problems for yourself if you rely on funcmaps for data, as you will make it harder to tell where the data comes from, harder to debug the handlers etc.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)