dongqian0763 2014-11-25 20:30
浏览 11
已采纳

将内容附加到特定部分中的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条回答 默认 最新

  • dongwei1855 2014-11-26 03:20
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测