Skip to content

text/template: The ability to output an io.Reader #25160

@smasher164

Description

@smasher164

Having the ability to templatize and concatenate multiple streams through a template would be highly useful. One can think of this as a generalization of the functionality provided by MultiReader, TeeReader, etc, except we'd have the ability to store stubs in files, and have more granular control of intermediate text and formatting.
For example, I'd like to be able to write something similar to the following:

r := // some predefined io.Reader...
t, _ := template.New("").Parse(`
<html>
    <head>
        <meta charset="UTF-8"><meta name="viewport" content="width=device-width, maximum-scale=1.0">
        <link href="/static/blog.css" rel="stylesheet">
    </head>
    <body>
        {{ . }}
    </body>
</html>
`)
t.Execute(os.Stdout, r)

Currently, I have a workaround using channels, however the overhead of channel communication doesn't make it worth using.

copyReader := func(c chan<- string, r io.Reader) {
	p := make([]byte, 100)
	for {
		n, err := r.Read(p)
		c <- string(p[:n])
		if err != nil {
			close(c)
			break
		}
	}
}
r := // some predefined io.Reader...
t, _ := template.New("").Parse(`
<html>
    <head>
        <meta charset="UTF-8"><meta name="viewport" content="width=device-width, maximum-scale=1.0">
        <link href="/static/blog.css" rel="stylesheet">
    </head>
    <body>
        {{range .}}{{.}}{{end}}
    </body>
</html>
`)
c := make(chan string)
go copyReader(c, r)
t.Execute(os.Stdout, c)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions