@@ -35,6 +35,8 @@ import (
35
35
36
36
"github.com/gohugoio/hugo/common/htime"
37
37
"github.com/gohugoio/hugo/common/paths"
38
+ "github.com/gohugoio/hugo/hugolib"
39
+ "github.com/gohugoio/hugo/tpl"
38
40
"golang.org/x/sync/errgroup"
39
41
40
42
"github.com/gohugoio/hugo/livereload"
@@ -522,20 +524,37 @@ func (c *commandeer) serve(s *serverCmd) error {
522
524
roots = []string {"" }
523
525
}
524
526
525
- templHandler := c .hugo ().Tmpl ()
526
- errTempl , found := templHandler .Lookup ("_server/error.html" )
527
- if ! found {
528
- panic ("template server/error.html not found" )
527
+ // Cache it here. The HugoSites object may be unavaialble later on due to intermitent configuration errors.
528
+ // To allow the en user to change the error template while the server is running, we use
529
+ // the freshest template we can provide.
530
+ var (
531
+ errTempl tpl.Template
532
+ templHandler tpl.TemplateHandler
533
+ )
534
+ getErrorTemplateAndHandler := func (h * hugolib.HugoSites ) (tpl.Template , tpl.TemplateHandler ) {
535
+ if h == nil {
536
+ return errTempl , templHandler
537
+ }
538
+ templHandler := h .Tmpl ()
539
+ errTempl , found := templHandler .Lookup ("_server/error.html" )
540
+ if ! found {
541
+ panic ("template server/error.html not found" )
542
+ }
543
+ return errTempl , templHandler
529
544
}
545
+ errTempl , templHandler = getErrorTemplateAndHandler (c .hugo ())
530
546
531
547
srv := & fileServer {
532
548
baseURLs : baseURLs ,
533
549
roots : roots ,
534
550
c : c ,
535
551
s : s ,
536
552
errorTemplate : func (ctx any ) (io.Reader , error ) {
553
+ // hugoTry does not block, getErrorTemplateAndHandler will fall back
554
+ // to cached values if nil.
555
+ templ , handler := getErrorTemplateAndHandler (c .hugoTry ())
537
556
b := & bytes.Buffer {}
538
- err := templHandler .Execute (errTempl , b , ctx )
557
+ err := handler .Execute (templ , b , ctx )
539
558
return b , err
540
559
},
541
560
}
0 commit comments