summaryrefslogtreecommitdiffstats
path: root/src/internal/lazytemplate
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 13:14:23 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 13:14:23 +0000
commit73df946d56c74384511a194dd01dbe099584fd1a (patch)
treefd0bcea490dd81327ddfbb31e215439672c9a068 /src/internal/lazytemplate
parentInitial commit. (diff)
downloadgolang-1.16-73df946d56c74384511a194dd01dbe099584fd1a.tar.xz
golang-1.16-73df946d56c74384511a194dd01dbe099584fd1a.zip
Adding upstream version 1.16.10.upstream/1.16.10upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/internal/lazytemplate')
-rw-r--r--src/internal/lazytemplate/lazytemplate.go52
1 files changed, 52 insertions, 0 deletions
diff --git a/src/internal/lazytemplate/lazytemplate.go b/src/internal/lazytemplate/lazytemplate.go
new file mode 100644
index 0000000..c83eaea
--- /dev/null
+++ b/src/internal/lazytemplate/lazytemplate.go
@@ -0,0 +1,52 @@
+// Copyright 2019 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package lazytemplate is a thin wrapper over text/template, allowing the use
+// of global template variables without forcing them to be parsed at init.
+package lazytemplate
+
+import (
+ "io"
+ "os"
+ "strings"
+ "sync"
+ "text/template"
+)
+
+// Template is a wrapper around text/template.Template, where the underlying
+// template will be parsed the first time it is needed.
+type Template struct {
+ name, text string
+
+ once sync.Once
+ tmpl *template.Template
+}
+
+func (r *Template) tp() *template.Template {
+ r.once.Do(r.build)
+ return r.tmpl
+}
+
+func (r *Template) build() {
+ r.tmpl = template.Must(template.New(r.name).Parse(r.text))
+ r.name, r.text = "", ""
+}
+
+func (r *Template) Execute(w io.Writer, data interface{}) error {
+ return r.tp().Execute(w, data)
+}
+
+var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test")
+
+// New creates a new lazy template, delaying the parsing work until it is first
+// needed. If the code is being run as part of tests, the template parsing will
+// happen immediately.
+func New(name, text string) *Template {
+ lt := &Template{name: name, text: text}
+ if inTest {
+ // In tests, always parse the templates early.
+ lt.tp()
+ }
+ return lt
+}