Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read file as template, execute it and write it back

Tags:

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 the file's content
  3. Executes the template by injecting the config variable
  4. Writes the rendered content to the console instead of 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()?

like image 923
user3147268 Avatar asked Sep 13 '15 16:09

user3147268


People also ask

How do I run a template file?

Open Word Template Files To open a Word template file, which contains a template library, right-click the default. dotx file name and select Open.

What does mean in Go template?

Go templates are a powerful method to customize output however you want, whether you're creating a web page, sending an e-mail, working with Buffalo, Go-Hugo, or just using some CLI such as kubectl. There're two packages operating with templates — text/template and html/template .

How do I parse an HTML template in Golang?

Golang Templates ParseFile and Execute In the render template Function first, the student struct is initialized with values. The Template is then parsed using the ParseFile() function from the html/template package. This creates a new template and parses the filename that is passed as input.


2 Answers

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.

like image 190
Bayta Darell Avatar answered Sep 22 '22 22:09

Bayta Darell


Here is a function I made with Cerise Limón's answer

func createFileUsingTemplate(t *template.Template, filename string, data interface{}) error {
    f, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer f.Close()

    err = t.Execute(f, data)
    if err != nil {
        return err
    }

    return nil
}
like image 37
CarlThePerson Avatar answered Sep 22 '22 22:09

CarlThePerson