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.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?