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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.