将内容添加到Go模板的特定部分中

huangapple go评论79阅读模式
英文:

Appending content to Go templates within a certain section

问题

我对在Go模板中的特定部分追加内容很感兴趣。由于模板有一个定义好的结构,每当我尝试在执行模板时追加新内容时,它会将新内容追加到先前执行的模板内容之后。

我目前的Go代码如下:

func appendToFile(filename string, template *template.Template, schema client.Schema) error {
	output, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	defer output.Close()

	data := map[string]interface{}{
		"schema": schema,
	}
	err = template.Execute(output, data)
	return err
}

我能想到的一个解决方案是每次都定位到先前追加的内容,并在那里写入新内容。但我不确定如何在Go中实现这一点。有人可以为我提供一个代码片段,或者建议一个更好的策略吗?

英文:

I am interested in appending content to a Go template but within a certain section of the template. Since the template has a structure defined, whenever I try to append new content on executing the template, it appends the new content to the previously executed template content:

Example template:

 type Client struct {
	Opts    *ClientOpts
	Schemas *Schemas
	Types   map[string]Schema

	Container *{{.schema.Id}}Client
	
  }

Actual output:

type Client struct {
    	Opts    *ClientOpts
    	Schemas *Schemas
    	Types   map[string]Schema
    
    	Container *abcClient
    	
      }

type Client struct {
    	Opts    *ClientOpts
    	Schemas *Schemas
    	Types   map[string]Schema
    
    	Container *xyzClient
    	
      }
}

Desired output:

type Client struct {
    	Opts    *ClientOpts
    	Schemas *Schemas
    	Types   map[string]Schema
    
    	Container *abcClient
        Container *xyzClient
    	
      }

My current Go code looks like this:

func appendToFile(filename string, template *template.Template, schema client.Schema) error {
	output, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		panic(err)
	}
	defer output.Close()

	data := map[string]interface{}{
		"schema": schema,
	}
	err = template.Execute(output, data)
	return err

}

One solution I can think of is to make a seek every time to the previous appended content and write the new content there. But I am not sure how to do that in Go. Could someone provide me with a code snippet for that or suggest a better strategy?

答案1

得分: 3

不要翻译代码部分,只翻译注释和字符串。以下是翻译的结果:

package main

import (
    "fmt"
    "os"
    "text/template"
)

var t = template.Must(template.New("").Parse(` type Client struct {
    Opts    *ClientOpts
    Schemas *Schemas
    Types   map[string]Schema

{{range .}}
    Container *{{.schema.Id}}Client{{end}}

}
`))

type schema struct {
    Id string
}

func main() {
    data := []map[string]interface{}{
        {"schema": schema{Id: "abcClient"}},
        {"schema": schema{Id: "xyzClient"}},
    }
    if err := t.Execute(os.Stdout, data); err != nil {
        fmt.Println(err)
    }
}

[ playground 上试一试](http://play.golang.org/p/T903Y8I77G).
英文:

Instead of appending the data, generate the output with one execution of the template:

package main

import (
    "fmt"
    "os"
    "text/template"
)

var t = template.Must(template.New("").Parse(` type Client struct {
    Opts    *ClientOpts
    Schemas *Schemas
    Types   map[string]Schema

{{range .}}
    Container *{{.schema.Id}}Client{{end}}

}
`))

type schema struct {
    Id string
}

func main() {
    data := []map[string]interface{}{
        {"schema": schema{Id: "abcClient"}},
        {"schema": schema{Id: "xyzClient"}},
    }
    if err := t.Execute(os.Stdout, data); err != nil {
        fmt.Println(err)
    }
}

Try it on the playground.

huangapple
  • 本文由 发表于 2014年11月26日 04:30:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/27136114.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定