Files
commerce/util/template/template.go
zeekay 1943f1c093 Hanzo Commerce
Multi-tenant commerce and billing: orders, subscriptions, invoices, plans,
usage metering and a credit ledger. One Go binary. MIT OR Apache-2.0.

Claude-Session: https://claude.ai/code/session_01SAtaDFm8VDiWrhYHNNtxMw
2026-09-23 21:52:16 -07:00

163 lines
4.1 KiB
Go

package template
import (
"os"
"github.com/aymerick/raymond"
"github.com/flosch/pongo2"
"github.com/zap-proto/zip"
"sync"
"github.com/hanzoai/commerce/config"
"github.com/hanzoai/commerce/log"
"github.com/hanzoai/commerce/models/types/country"
"github.com/hanzoai/commerce/models/types/currency"
"github.com/hanzoai/commerce/models/types/thankyou"
"github.com/hanzoai/commerce/util/fs"
"github.com/hanzoai/commerce/util/json"
)
var cwd, _ = os.Getwd()
func createMap(pairs []interface{}) map[string]interface{} {
// Create map from pairs
m := make(map[string]interface{})
for i := 0; i < len(pairs); i = i + 2 {
m[pairs[i].(string)] = pairs[i+1]
}
return m
}
func createContext(pairs []interface{}) pongo2.Context {
ctx := pongo2.Context{}
m := createMap(pairs)
for k, v := range m {
ctx[k] = v
}
return ctx
}
func createTemplateSet() *pongo2.TemplateSet {
loader := pongo2.MustNewLocalFileSystemLoader("")
set := pongo2.NewSet("default", loader)
set.Debug = config.IsDevelopment
set.Globals["config"] = config.Get()
set.Globals["isDevelopment"] = config.IsDevelopment
set.Globals["isProduction"] = config.IsProduction
set.Globals["isStaging"] = config.IsStaging
set.Globals["siteTitle"] = config.SiteTitle
set.Globals["urlFor"] = func(moduleName string, args ...string) string {
return config.UrlFor(moduleName, args...)
}
// DEPRECATED: Remove as soon as all templates are updated to use `urlFor`.
set.Globals["staticUrl"] = config.StaticUrl
set.Globals["moduleUrl"] = func(moduleName string, args ...string) string {
return config.UrlFor(moduleName, args...)
}
set.Globals["jsonify"] = json.Encode
set.Globals["constants"] = struct {
CountriesByISOCode map[string]country.Country
Countries []country.Country
CurrencyTypes []currency.Type
ThankYouTypes []thankyou.Type
}{
CountriesByISOCode: country.ByISO(),
Countries: country.All(),
CurrencyTypes: currency.Types,
ThankYouTypes: thankyou.Types,
}
return set
}
// templateSet is built on FIRST RENDER, not at init.
//
// It was a package-level var, so every process linking this package built the whole
// global environment before it could listen — including a `constants` global holding
// all 249 countries, which forced 5.1 MB of YAML through a parser (121 ms, measured)
// for a value no template in this repository reads. A template set is what renders a
// template; a process that renders none needs none.
var templateSet = sync.OnceValue(createTemplateSet)
func getTemplate(path string) *pongo2.Template {
// All templates are expected to be in templates dir
templatePath := cwd + "/templates/" + path
// Get template from cache
template, err := templateSet().FromCache(templatePath)
if err != nil {
log.Panic("Unable to fetch template: %v\n\n%v", templatePath, err)
}
return template
}
func Render(c *zip.Ctx, path string, pairs ...interface{}) error {
// Get template
template := getTemplate(path)
// Create pongo context
ctx := createContext(pairs)
// Render template to a string
out, err := template.Execute(ctx)
if err != nil {
log.Panic("Unable to render template: %v\n\n%v", path, err)
}
// Set content type and write the rendered body
c.SetHeader("Content-Type", "text/html; charset=utf-8")
return c.String(200, out)
}
func RenderEmail(path string, data map[string]interface{}) string {
// Get template
templatePath := cwd + "/templates/email/" + path + ".html"
template := fs.ReadFile(templatePath)
// Render template
out := raymond.MustRender(string(template), data)
return out
}
func RenderPath(path string, pairs ...interface{}) string {
// Get template
template := getTemplate(path)
// Create pongo context
ctx := createContext(pairs)
// Render template
out, err := template.Execute(ctx)
if err != nil {
log.Panic("Unable to render template: %v\n\n%v", path, err)
}
return out
}
func RenderString(template string, pairs ...interface{}) string {
// Create pongo context
ctx := createContext(pairs)
// Render template
str, err := pongo2.RenderTemplateString(template, ctx)
if err != nil {
log.Panic("Unable to render template: %v", err)
}
return str
}