Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RenderPage Callback function #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions html.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,22 @@ import (
"github.com/rivo/sessions"
)

//Template data provider callback function signature
type tmplDataProvider func(*http.Request) map[string]interface{}

var (
// The list of htmlTemplates that have already been parsed.
htmlTemplates map[string]*template.Template
htmlTemplatesMutex sync.Mutex
renderPageDataCb tmplDataProvider
)

//SetRenderPageDataCb sets the callback handler that is invoked when RenderPage is executed
//The provided map is accessible within a template though a key called "extdata".
func SetRenderPageDataCb(f tmplDataProvider) {
renderPageDataCb = f
}

// retrieveTemplate returns an HTML template with the given filename (located in
// Config.HTMLTemplateDir or a subdirectory of it, depending on the value of
// Config.Internationalization), retrieving it from the cache if
Expand Down Expand Up @@ -123,6 +133,14 @@ func RenderPage(response http.ResponseWriter, request *http.Request, htmlTemplat
response.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
response.Header().Set("Pragma", "no-cache")
response.Header().Set("Expires", "0")

dataMap, ok := data.(map[string]interface{})
// Inject extended template data provided by a callback function
if ok && renderPageDataCb != nil {
dataMap["extdata"] = renderPageDataCb(request)
data = dataMap
}

if err := tmpl.Execute(response, data); err != nil {
programError(response, fmt.Sprintf(`Template "%s" could not be executed`, htmlTemplate), "Could not execute template", err)
}
Expand Down