-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
runtime.go
891 lines (788 loc) · 22.9 KB
/
runtime.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
package templ
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"html"
"html/template"
"io"
"net/http"
"os"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/a-h/templ/safehtml"
)
// Types exposed by all components.
// Component is the interface that all templates implement.
type Component interface {
// Render the template.
Render(ctx context.Context, w io.Writer) error
}
// ComponentFunc converts a function that matches the Component interface's
// Render method into a Component.
type ComponentFunc func(ctx context.Context, w io.Writer) error
// Render the template.
func (cf ComponentFunc) Render(ctx context.Context, w io.Writer) error {
return cf(ctx, w)
}
func WithChildren(ctx context.Context, children Component) context.Context {
ctx, v := getContext(ctx)
v.children = &children
return ctx
}
func ClearChildren(ctx context.Context) context.Context {
_, v := getContext(ctx)
v.children = nil
return ctx
}
// NopComponent is a component that doesn't render anything.
var NopComponent = ComponentFunc(func(ctx context.Context, w io.Writer) error { return nil })
// GetChildren from the context.
func GetChildren(ctx context.Context) Component {
_, v := getContext(ctx)
if v.children == nil {
return NopComponent
}
return *v.children
}
// ComponentHandler is a http.Handler that renders components.
type ComponentHandler struct {
Component Component
Status int
ContentType string
ErrorHandler func(r *http.Request, err error) http.Handler
}
const componentHandlerErrorMessage = "templ: failed to render template"
// ServeHTTP implements the http.Handler interface.
func (ch ComponentHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Since the component may error, write to a buffer first.
// This prevents partial responses from being written to the client.
buf := GetBuffer()
defer ReleaseBuffer(buf)
err := ch.Component.Render(r.Context(), buf)
if err != nil {
if ch.ErrorHandler != nil {
w.Header().Set("Content-Type", ch.ContentType)
ch.ErrorHandler(r, err).ServeHTTP(w, r)
return
}
http.Error(w, componentHandlerErrorMessage, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", ch.ContentType)
if ch.Status != 0 {
w.WriteHeader(ch.Status)
}
// Ignore write error like http.Error() does, because there is
// no way to recover at this point.
_, _ = w.Write(buf.Bytes())
}
// Handler creates a http.Handler that renders the template.
func Handler(c Component, options ...func(*ComponentHandler)) *ComponentHandler {
ch := &ComponentHandler{
Component: c,
ContentType: "text/html; charset=utf-8",
}
for _, o := range options {
o(ch)
}
return ch
}
// WithStatus sets the HTTP status code returned by the ComponentHandler.
func WithStatus(status int) func(*ComponentHandler) {
return func(ch *ComponentHandler) {
ch.Status = status
}
}
// WithConentType sets the Content-Type header returned by the ComponentHandler.
func WithContentType(contentType string) func(*ComponentHandler) {
return func(ch *ComponentHandler) {
ch.ContentType = contentType
}
}
// WithErrorHandler sets the error handler used if rendering fails.
func WithErrorHandler(eh func(r *http.Request, err error) http.Handler) func(*ComponentHandler) {
return func(ch *ComponentHandler) {
ch.ErrorHandler = eh
}
}
// EscapeString escapes HTML text within templates.
func EscapeString(s string) string {
return html.EscapeString(s)
}
// Bool attribute value.
func Bool(value bool) bool {
return value
}
// Classes for CSS.
// Supported types are string, ConstantCSSClass, ComponentCSSClass, map[string]bool.
func Classes(classes ...any) CSSClasses {
return CSSClasses(classes)
}
// CSSClasses is a slice of CSS classes.
type CSSClasses []any
// String returns the names of all CSS classes.
func (classes CSSClasses) String() string {
if len(classes) == 0 {
return ""
}
cp := newCSSProcessor()
for _, v := range classes {
cp.Add(v)
}
return cp.String()
}
func newCSSProcessor() *cssProcessor {
return &cssProcessor{
classNameToEnabled: make(map[string]bool),
}
}
type cssProcessor struct {
classNameToEnabled map[string]bool
orderedNames []string
}
func (cp *cssProcessor) Add(item any) {
switch c := item.(type) {
case []string:
for _, className := range c {
cp.AddClassName(className, true)
}
case string:
cp.AddClassName(c, true)
case ConstantCSSClass:
cp.AddClassName(c.ClassName(), true)
case ComponentCSSClass:
cp.AddClassName(c.ClassName(), true)
case map[string]bool:
// In Go, map keys are iterated in a randomized order.
// So the keys in the map must be sorted to produce consistent output.
keys := make([]string, len(c))
var i int
for key := range c {
keys[i] = key
i++
}
sort.Strings(keys)
for _, className := range keys {
cp.AddClassName(className, c[className])
}
case []KeyValue[string, bool]:
for _, kv := range c {
cp.AddClassName(kv.Key, kv.Value)
}
case KeyValue[string, bool]:
cp.AddClassName(c.Key, c.Value)
case []KeyValue[CSSClass, bool]:
for _, kv := range c {
cp.AddClassName(kv.Key.ClassName(), kv.Value)
}
case KeyValue[CSSClass, bool]:
cp.AddClassName(c.Key.ClassName(), c.Value)
case CSSClasses:
for _, item := range c {
cp.Add(item)
}
case func() CSSClass:
cp.AddClassName(c().ClassName(), true)
default:
cp.AddClassName(unknownTypeClassName, true)
}
}
func (cp *cssProcessor) AddClassName(className string, enabled bool) {
cp.classNameToEnabled[className] = enabled
cp.orderedNames = append(cp.orderedNames, className)
}
func (cp *cssProcessor) String() string {
// Order the outputs according to how they were input, and remove disabled names.
rendered := make(map[string]any, len(cp.classNameToEnabled))
var names []string
for _, name := range cp.orderedNames {
if enabled := cp.classNameToEnabled[name]; !enabled {
continue
}
if _, hasBeenRendered := rendered[name]; hasBeenRendered {
continue
}
names = append(names, name)
rendered[name] = struct{}{}
}
return strings.Join(names, " ")
}
// KeyValue is a key and value pair.
type KeyValue[TKey comparable, TValue any] struct {
Key TKey `json:"name"`
Value TValue `json:"value"`
}
// KV creates a new key/value pair from the input key and value.
func KV[TKey comparable, TValue any](key TKey, value TValue) KeyValue[TKey, TValue] {
return KeyValue[TKey, TValue]{
Key: key,
Value: value,
}
}
const unknownTypeClassName = "--templ-css-class-unknown-type"
// Class returns a CSS class name.
// Deprecated: use a string instead.
func Class(name string) CSSClass {
return SafeClass(name)
}
// SafeClass bypasses CSS class name validation.
// Deprecated: use a string instead.
func SafeClass(name string) CSSClass {
return ConstantCSSClass(name)
}
// CSSClass provides a class name.
type CSSClass interface {
ClassName() string
}
// ConstantCSSClass is a string constant of a CSS class name.
// Deprecated: use a string instead.
type ConstantCSSClass string
// ClassName of the CSS class.
func (css ConstantCSSClass) ClassName() string {
return string(css)
}
// ComponentCSSClass is a templ.CSS
type ComponentCSSClass struct {
// ID of the class, will be autogenerated.
ID string
// Definition of the CSS.
Class SafeCSS
}
// ClassName of the CSS class.
func (css ComponentCSSClass) ClassName() string {
return css.ID
}
// CSSID calculates an ID.
func CSSID(name string, css string) string {
sum := sha256.Sum256([]byte(css))
hp := hex.EncodeToString(sum[:])[0:4]
// Benchmarking showed this was fastest, and with fewest allocations (1).
// Using strings.Builder (2 allocs).
// Using fmt.Sprintf (3 allocs).
return name + "_" + hp
}
// NewCSSMiddleware creates HTTP middleware that renders a global stylesheet of ComponentCSSClass
// CSS if the request path matches, or updates the HTTP context to ensure that any handlers that
// use templ.Components skip rendering <style> elements for classes that are included in the global
// stylesheet. By default, the stylesheet path is /styles/templ.css
func NewCSSMiddleware(next http.Handler, classes ...CSSClass) CSSMiddleware {
return CSSMiddleware{
Path: "/styles/templ.css",
CSSHandler: NewCSSHandler(classes...),
Next: next,
}
}
// CSSMiddleware renders a global stylesheet.
type CSSMiddleware struct {
Path string
CSSHandler CSSHandler
Next http.Handler
}
func (cssm CSSMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == cssm.Path {
cssm.CSSHandler.ServeHTTP(w, r)
return
}
// Add registered classes to the context.
ctx, v := getContext(r.Context())
for _, c := range cssm.CSSHandler.Classes {
v.addClass(c.ID)
}
// Serve the request. Templ components will use the updated context
// to know to skip rendering <style> elements for any component CSS
// classes that have been included in the global stylesheet.
cssm.Next.ServeHTTP(w, r.WithContext(ctx))
}
// NewCSSHandler creates a handler that serves a stylesheet containing the CSS of the
// classes passed in. This is used by the CSSMiddleware to provide global stylesheets
// for templ components.
func NewCSSHandler(classes ...CSSClass) CSSHandler {
ccssc := make([]ComponentCSSClass, 0, len(classes))
for _, c := range classes {
ccss, ok := c.(ComponentCSSClass)
if !ok {
continue
}
ccssc = append(ccssc, ccss)
}
return CSSHandler{
Classes: ccssc,
}
}
// CSSHandler is a HTTP handler that serves CSS.
type CSSHandler struct {
Logger func(err error)
Classes []ComponentCSSClass
}
func (cssh CSSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/css")
for _, c := range cssh.Classes {
_, err := w.Write([]byte(c.Class))
if err != nil && cssh.Logger != nil {
cssh.Logger(err)
}
}
}
// RenderCSSItems renders the CSS to the writer, if the items haven't already been rendered.
func RenderCSSItems(ctx context.Context, w io.Writer, classes ...any) (err error) {
if len(classes) == 0 {
return nil
}
_, v := getContext(ctx)
sb := new(strings.Builder)
renderCSSItemsToBuilder(sb, v, classes...)
if sb.Len() > 0 {
if _, err = io.WriteString(w, `<style type="text/css">`); err != nil {
return err
}
if _, err = io.WriteString(w, sb.String()); err != nil {
return err
}
if _, err = io.WriteString(w, `</style>`); err != nil {
return err
}
}
return nil
}
func renderCSSItemsToBuilder(sb *strings.Builder, v *contextValue, classes ...any) {
for _, c := range classes {
switch ccc := c.(type) {
case ComponentCSSClass:
if !v.hasClassBeenRendered(ccc.ID) {
sb.WriteString(string(ccc.Class))
v.addClass(ccc.ID)
}
case KeyValue[ComponentCSSClass, bool]:
if !ccc.Value {
continue
}
renderCSSItemsToBuilder(sb, v, ccc.Key)
case KeyValue[CSSClass, bool]:
if !ccc.Value {
continue
}
renderCSSItemsToBuilder(sb, v, ccc.Key)
case CSSClasses:
renderCSSItemsToBuilder(sb, v, ccc...)
case func() CSSClass:
renderCSSItemsToBuilder(sb, v, ccc())
case []string:
// Skip. These are class names, not CSS classes.
case string:
// Skip. This is a class name, not a CSS class.
case ConstantCSSClass:
// Skip. This is a class name, not a CSS class.
case CSSClass:
// Skip. This is a class name, not a CSS class.
case map[string]bool:
// Skip. These are class names, not CSS classes.
case KeyValue[string, bool]:
// Skip. These are class names, not CSS classes.
case []KeyValue[string, bool]:
// Skip. These are class names, not CSS classes.
case KeyValue[ConstantCSSClass, bool]:
// Skip. These are class names, not CSS classes.
case []KeyValue[ConstantCSSClass, bool]:
// Skip. These are class names, not CSS classes.
}
}
}
// SafeCSS is CSS that has been sanitized.
type SafeCSS string
type SafeCSSProperty string
var safeCSSPropertyType = reflect.TypeOf(SafeCSSProperty(""))
// SanitizeCSS sanitizes CSS properties to ensure that they are safe.
func SanitizeCSS[T ~string](property string, value T) SafeCSS {
if reflect.TypeOf(value) == safeCSSPropertyType {
return SafeCSS(safehtml.SanitizeCSSProperty(property) + ":" + string(value) + ";")
}
p, v := safehtml.SanitizeCSS(property, string(value))
return SafeCSS(p + ":" + v + ";")
}
// Hyperlink sanitization.
// FailedSanitizationURL is returned if a URL fails sanitization checks.
const FailedSanitizationURL = SafeURL("about:invalid#TemplFailedSanitizationURL")
// URL sanitizes the input string s and returns a SafeURL.
func URL(s string) SafeURL {
if i := strings.IndexRune(s, ':'); i >= 0 && !strings.ContainsRune(s[:i], '/') {
protocol := s[:i]
if !strings.EqualFold(protocol, "http") && !strings.EqualFold(protocol, "https") && !strings.EqualFold(protocol, "mailto") {
return FailedSanitizationURL
}
}
return SafeURL(s)
}
// SafeURL is a URL that has been sanitized.
type SafeURL string
// Attributes is an alias to map[string]any made for spread attributes.
type Attributes map[string]any
// sortedKeys returns the keys of a map in sorted order.
func sortedKeys(m map[string]any) (keys []string) {
keys = make([]string, len(m))
var i int
for k := range m {
keys[i] = k
i++
}
sort.Strings(keys)
return keys
}
func writeStrings(w io.Writer, ss ...string) (err error) {
for _, s := range ss {
if _, err = io.WriteString(w, s); err != nil {
return err
}
}
return nil
}
func RenderAttributes(ctx context.Context, w io.Writer, attributes Attributes) (err error) {
for _, key := range sortedKeys(attributes) {
value := attributes[key]
switch value := value.(type) {
case string:
if err = writeStrings(w, ` `, EscapeString(key), `="`, EscapeString(value), `"`); err != nil {
return err
}
case *string:
if value != nil {
if err = writeStrings(w, ` `, EscapeString(key), `="`, EscapeString(*value), `"`); err != nil {
return err
}
}
case bool:
if value {
if err = writeStrings(w, ` `, EscapeString(key)); err != nil {
return err
}
}
case *bool:
if value != nil && *value {
if err = writeStrings(w, ` `, EscapeString(key)); err != nil {
return err
}
}
case KeyValue[string, bool]:
if value.Value {
if err = writeStrings(w, ` `, EscapeString(key), `="`, EscapeString(value.Key), `"`); err != nil {
return err
}
}
case KeyValue[bool, bool]:
if value.Value && value.Key {
if err = writeStrings(w, ` `, EscapeString(key)); err != nil {
return err
}
}
case func() bool:
if value() {
if err = writeStrings(w, ` `, EscapeString(key)); err != nil {
return err
}
}
}
}
return nil
}
// Script handling.
func safeEncodeScriptParams(escapeHTML bool, params []any) []string {
encodedParams := make([]string, len(params))
for i := 0; i < len(encodedParams); i++ {
enc, _ := json.Marshal(params[i])
if !escapeHTML {
encodedParams[i] = string(enc)
continue
}
encodedParams[i] = EscapeString(string(enc))
}
return encodedParams
}
// SafeScript encodes unknown parameters for safety for inside HTML attributes.
func SafeScript(functionName string, params ...any) string {
encodedParams := safeEncodeScriptParams(true, params)
sb := new(strings.Builder)
sb.WriteString(functionName)
sb.WriteRune('(')
sb.WriteString(strings.Join(encodedParams, ","))
sb.WriteRune(')')
return sb.String()
}
// SafeScript encodes unknown parameters for safety for inline scripts.
func SafeScriptInline(functionName string, params ...any) string {
encodedParams := safeEncodeScriptParams(false, params)
sb := new(strings.Builder)
sb.WriteString(functionName)
sb.WriteRune('(')
sb.WriteString(strings.Join(encodedParams, ","))
sb.WriteRune(')')
return sb.String()
}
type contextKeyType int
const contextKey = contextKeyType(0)
type contextValue struct {
ss map[string]struct{}
children *Component
}
func (v *contextValue) addScript(s string) {
if v.ss == nil {
v.ss = map[string]struct{}{}
}
v.ss["script_"+s] = struct{}{}
}
func (v *contextValue) hasScriptBeenRendered(s string) (ok bool) {
if v.ss == nil {
v.ss = map[string]struct{}{}
}
_, ok = v.ss["script_"+s]
return
}
func (v *contextValue) addClass(s string) {
if v.ss == nil {
v.ss = map[string]struct{}{}
}
v.ss["class_"+s] = struct{}{}
}
func (v *contextValue) hasClassBeenRendered(s string) (ok bool) {
if v.ss == nil {
v.ss = map[string]struct{}{}
}
_, ok = v.ss["class_"+s]
return
}
// InitializeContext initializes context used to store internal state used during rendering.
func InitializeContext(ctx context.Context) context.Context {
if _, ok := ctx.Value(contextKey).(*contextValue); ok {
return ctx
}
v := &contextValue{}
ctx = context.WithValue(ctx, contextKey, v)
return ctx
}
func getContext(ctx context.Context) (context.Context, *contextValue) {
v, ok := ctx.Value(contextKey).(*contextValue)
if !ok {
ctx = InitializeContext(ctx)
v = ctx.Value(contextKey).(*contextValue)
}
return ctx, v
}
// ComponentScript is a templ Script template.
type ComponentScript struct {
// Name of the script, e.g. print.
Name string
// Function to render.
Function string
// Call of the function in JavaScript syntax, including parameters, and
// ensures parameters are HTML escaped; useful for injecting into HTML
// attributes like onclick, onhover, etc.
//
// Given:
// functionName("some string",12345)
// It would render:
// __templ_functionName_sha("some string",12345))
//
// This is can be injected into HTML attributes:
// <button onClick="__templ_functionName_sha("some string",12345))">Click Me</button>
Call string
// Call of the function in JavaScript syntax, including parameters. It
// does not HTML escape parameters; useful for directly calling in script
// elements.
//
// Given:
// functionName("some string",12345)
// It would render:
// __templ_functionName_sha("some string",12345))
//
// This is can be used to call the function inside a script tag:
// <script>__templ_functionName_sha("some string",12345))</script>
CallInline string
}
var _ Component = ComponentScript{}
func (c ComponentScript) Render(ctx context.Context, w io.Writer) error {
err := RenderScriptItems(ctx, w, c)
if err != nil {
return err
}
if len(c.Call) > 0 {
if _, err = io.WriteString(w, `<script type="text/javascript">`); err != nil {
return err
}
if _, err = io.WriteString(w, c.CallInline); err != nil {
return err
}
if _, err = io.WriteString(w, `</script>`); err != nil {
return err
}
}
return nil
}
// RenderScriptItems renders a <script> element, if the script has not already been rendered.
func RenderScriptItems(ctx context.Context, w io.Writer, scripts ...ComponentScript) (err error) {
if len(scripts) == 0 {
return nil
}
_, v := getContext(ctx)
sb := new(strings.Builder)
for _, s := range scripts {
if !v.hasScriptBeenRendered(s.Name) {
sb.WriteString(s.Function)
v.addScript(s.Name)
}
}
if sb.Len() > 0 {
if _, err = io.WriteString(w, `<script type="text/javascript">`); err != nil {
return err
}
if _, err = io.WriteString(w, sb.String()); err != nil {
return err
}
if _, err = io.WriteString(w, `</script>`); err != nil {
return err
}
}
return nil
}
var bufferPool = sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
func GetBuffer() *bytes.Buffer {
return bufferPool.Get().(*bytes.Buffer)
}
func ReleaseBuffer(b *bytes.Buffer) {
b.Reset()
bufferPool.Put(b)
}
// JoinStringErrs joins an optional list of errors.
func JoinStringErrs(s string, errs ...error) (string, error) {
return s, errors.Join(errs...)
}
// Error returned during template rendering.
type Error struct {
Err error
// FileName of the template file.
FileName string
// Line index of the error.
Line int
// Col index of the error.
Col int
}
func (e Error) Error() string {
if e.FileName == "" {
e.FileName = "templ"
}
return fmt.Sprintf("%s: error at line %d, col %d: %v", e.FileName, e.Line, e.Col, e.Err)
}
func (e Error) Unwrap() error {
return e.Err
}
// Raw renders the input HTML to the output without applying HTML escaping.
//
// Use of this component presents a security risk - the HTML should come from
// a trusted source, because it will be included as-is in the output.
func Raw[T ~string](html T, errs ...error) Component {
return ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
if err = errors.Join(errs...); err != nil {
return err
}
_, err = io.WriteString(w, string(html))
return err
})
}
// FromGoHTML creates a templ Component from a Go html/template template.
func FromGoHTML(t *template.Template, data any) Component {
return ComponentFunc(func(ctx context.Context, w io.Writer) (err error) {
return t.Execute(w, data)
})
}
// ToGoHTML renders the component to a Go html/template template.HTML string.
func ToGoHTML(ctx context.Context, c Component) (s template.HTML, err error) {
b := GetBuffer()
defer ReleaseBuffer(b)
if err = c.Render(ctx, b); err != nil {
return
}
s = template.HTML(b.String())
return
}
// WriteWatchModeString is used when rendering templates in development mode.
// the generator would have written non-go code to the _templ.txt file, which
// is then read by this function and written to the output.
func WriteWatchModeString(w *bytes.Buffer, lineNum int) error {
_, path, _, _ := runtime.Caller(1)
if !strings.HasSuffix(path, "_templ.go") {
return errors.New("templ: WriteWatchModeString can only be called from _templ.go")
}
txtFilePath := strings.Replace(path, "_templ.go", "_templ.txt", 1)
literals, err := getWatchedStrings(txtFilePath)
if err != nil {
return fmt.Errorf("templ: failed to cache strings: %w", err)
}
if lineNum > len(literals) {
return errors.New("templ: failed to find line " + strconv.Itoa(lineNum) + " in " + txtFilePath)
}
unquoted, err := strconv.Unquote(`"` + literals[lineNum-1] + `"`)
if err != nil {
return err
}
_, err = io.WriteString(io.Writer(w), unquoted)
return err
}
var (
watchModeCache = map[string]watchState{}
watchStateMutex sync.Mutex
)
type watchState struct {
modTime time.Time
strings []string
}
func getWatchedStrings(txtFilePath string) ([]string, error) {
watchStateMutex.Lock()
defer watchStateMutex.Unlock()
state, cached := watchModeCache[txtFilePath]
if !cached {
return cacheStrings(txtFilePath)
}
if time.Since(state.modTime) < time.Millisecond*100 {
return state.strings, nil
}
info, err := os.Stat(txtFilePath)
if err != nil {
return nil, fmt.Errorf("templ: failed to stat %s: %w", txtFilePath, err)
}
if !info.ModTime().After(state.modTime) {
return state.strings, nil
}
return cacheStrings(txtFilePath)
}
func cacheStrings(txtFilePath string) ([]string, error) {
txtFile, err := os.Open(txtFilePath)
if err != nil {
return nil, fmt.Errorf("templ: failed to open %s: %w", txtFilePath, err)
}
defer txtFile.Close()
info, err := txtFile.Stat()
if err != nil {
return nil, fmt.Errorf("templ: failed to stat %s: %w", txtFilePath, err)
}
all, err := io.ReadAll(txtFile)
if err != nil {
return nil, fmt.Errorf("templ: failed to read %s: %w", txtFilePath, err)
}
literals := strings.Split(string(all), "\n")
watchModeCache[txtFilePath] = watchState{
modTime: info.ModTime(),
strings: literals,
}
return literals, nil
}