DEV Community

Cover image for Template File Processing in Go
Kirk Lewis
Kirk Lewis

Posted on

Template File Processing in Go

In a previous post I demonstrated how to get a Go template's interpolated string result. However, if you just want to interpolate and then write the string result straight to file, this post demonstrates how.

The Template File

The following text can be saved to a file templates/greeting.tmpl.

{{.Greeting}} {{.Name}}!

The template string above contains two annotations .Greeting and .Name which is enough for this demonstration.

Execute and Write

The first argument of the text/template package's Execute function uses an io.Writer interface. As such, if we pass this argument an os.File, its write function will be used to write the processed template bytes straight to file.

Add the following code to a file named process-file.go .

package main

import (

func main() {
    // variables
    vars := make(map[string]interface{})
    vars["Greeting"] = "Hello"
    vars["Name"] = "Dev"

    // parse the template
    tmpl, _ := template.ParseFiles("templates/greeting.tmpl")

    // create a new file
    file, _ := os.Create("greeting.txt")
    defer file.Close()

    // apply the template to the vars map and write the result to file.
    tmpl.Execute(file, vars)

For brevity, I have omitted error checking in the code above by using an underscore

Run the file

go run process-file.go

Running the line above should create a file named greeting.txt. Check the contents of this file.

cat greeting.txt

Hello Dev!

Thank you for reading! The code used in this post can be found as a Github gist here.

Discussion (3)

kirklewis profile image
Kirk Lewis Author

Thank you! I might cover that topic in the future.