dtmwnqng38644 2015-09-13 16:21
浏览 38
已采纳

读取文件作为模板,执行并写回

I'm trying to parse CSS files in which variables can be injected that are defined in a config file. Currently the function does:

  1. Opens the file based on the given path argument
  2. Parses it the file's content
  3. Executes the template by injecting the config variable
  4. Writes the rendered content to the console instead into the original file
func parse(path string) {
    f, err := ioutil.ReadFile(path)

    if err != nil {
        log.Print(err)
        return
    }

    // Parse requires a string
    t, err := template.New("css").Parse(string(f))

    if err != nil {
        log.Print(err)
        return
    }

    // A sample config
    config := map[string]string {
        "textColor": "#abcdef",
        "linkColorHover": "#ffaacc",
    }   

    // Execute needs some sort of io.Writer
    err = t.Execute(os.Stdout, config)  

    if err != nil {
        log.Print("Can't execute ", path)
    }
}

My problem is that template.Parse() requires the content as string and template.Execute() an io.Writer as argument. I tried to open the file with os.Open() which returns a file object that implements the io.Writer interface. But how can I get the file's content as a string from such a file object in order to use it with Parse()?

  • 写回答

1条回答 默认 最新

  • dongmuzhan4705 2015-09-13 17:39
    关注

    Use ParseFiles to parse the template. This code basically does the same thing as calling ReadFile, template.New and Parse as in the question, but it's shorter.

    t, err := template.ParseFiles(path)
    if err != nil {
        log.Print(err)
        return
    }
    

    Use os.Create to open the output file.

    f, err := os.Create(path)
    if err != nil {
        log.Println("create file: ", err)
        return
    }
    

    A file is an io.Writer. You can execute the template directly to the open file:

    err = t.Execute(f, config)
    if err != nil {
        log.Print("execute: ", err)
        return
    }
    

    Close the file when done.

    f.Close()
    

    Complete working example on the playground.

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

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路