github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/webapp/template.go (about)

     1  // Copyright 2020 The WPT Dashboard Project. All rights reserved.
     2  // Use of this source code is governed by a BSD-style license that can be
     3  // found in the LICENSE file.
     4  
     5  //go:generate packr2
     6  
     7  package webapp
     8  
     9  import (
    10  	"html/template"
    11  	"net/http"
    12  
    13  	"github.com/gobuffalo/packr/v2"
    14  	"github.com/web-platform-tests/wpt.fyi/shared"
    15  )
    16  
    17  // templates contains all of the template objects parsed from templates/*,
    18  // created once at startup. Use RenderTemplate to render responses.
    19  var templates *template.Template
    20  
    21  func init() {
    22  	box := packr.New("html templates", "./templates/")
    23  	templates = template.New("all.html")
    24  	for _, t := range box.List() {
    25  		tmpl := templates.New(t)
    26  		body, err := box.FindString(t)
    27  		if err != nil {
    28  			panic(err)
    29  		} else if _, err = tmpl.Parse(body); err != nil {
    30  			panic(err)
    31  		}
    32  	}
    33  }
    34  
    35  type templateData struct {
    36  	Data interface{}
    37  	User *shared.User
    38  }
    39  
    40  // RenderTemplate renders an HTML template to a response. The provided data
    41  // will be available in the Data field in the template. There are some
    42  // additional fields extracted from the request (e.g. User) available in the
    43  // template if the request is not nil.
    44  // If an error is encountered, appropriate error codes and messages will be set
    45  // on the response; do not write additional data to the response after calling
    46  // this function.
    47  func RenderTemplate(w http.ResponseWriter, r *http.Request, name string, data interface{}) {
    48  	tdata := templateData{Data: data}
    49  	if r != nil {
    50  		ctx := r.Context()
    51  		ds := shared.NewAppEngineDatastore(ctx, false)
    52  		tdata.User, _ = shared.GetUserFromCookie(ctx, ds, r)
    53  	}
    54  	if err := templates.ExecuteTemplate(w, name, tdata); err != nil {
    55  		http.Error(w, err.Error(), http.StatusInternalServerError)
    56  	}
    57  }