Parse Templates From Any fs.FS

Load text templates through template.ParseFS from any fs.FS source, so tests can use fstest.MapFS while production swaps in embed.FS untouched.

GoConfig Management

Code

snippet
package main

import (
	"fmt"
	"strings"
	"testing/fstest"
	"text/template"
)

type task struct {
	Name   string
	Status string
}

func main() {
	// 任何 fs.FS 都是合法模板源:测试用 fstest.MapFS,生产换 embed.FS 调用不变
	source := fstest.MapFS{
		"tmpl/head.tmpl": {Data: []byte("== {{.Title}} ==\n")},
		"tmpl/row.tmpl":  {Data: []byte("{{.Name}}: {{.Status}}\n")},
	}

	tmpl, err := template.ParseFS(source, "tmpl/*.tmpl")
	if err != nil {
		fmt.Println("parse:", err)
		return
	}

	var report strings.Builder
	if err := tmpl.ExecuteTemplate(&report, "head.tmpl", map[string]string{"Title": "nightly deploy"}); err != nil {
		fmt.Println("execute:", err)
		return
	}
	for _, t := range []task{{Name: "build", Status: "ok"}, {Name: "sign", Status: "ok"}, {Name: "upload", Status: "retry"}} {
		if err := tmpl.ExecuteTemplate(&report, "row.tmpl", t); err != nil {
			fmt.Println("execute:", err)
			return
		}
	}
	fmt.Print(report.String())
}

Line-by-line reading

Parse Templates From Any fs.FS keeps everything in the function main.

The cycling part of this snippet is for _, t := range []task{{Name: "build", Status: "ok"}, {Name: "sign", Status: "ok"}, {Name: "upl…. err is inspected at 2 call sites before any result is trusted.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func main()

The run prints parse:, execute: — each prefix names the step that produced it.

Core lines

for _, t := range []task{{Name: "build", Status: "ok"}, {Name: "sign", Status: "ok"}, {Name: "upload", Status: "retry"}} {
	if err := tmpl.ExecuteTemplate(&report, "row.tmpl", t); err != nil {
		fmt.Println("execute:", err)
		return
	}
}
if err != nil {
	fmt.Println("parse:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Parse Templates From Any fs.FS print when run?
No setup needed: run the file and look for labeled lines like `parse:`, `execute:` in the output.