Advanced Techniques
Template Composition and Inheritance
Template Embedding
package main
import (
"os"
"text/template"
)
func main() {
baseTemplate := `
{{define "base"}}
Base Template
{{block "content" .}}
Default Content
{{end}}
{{end}}
`
specificTemplate := `
{{define "content"}}
LabEx Specific Content
{{end}}
`
tmpl := template.Must(template.New("base").Parse(baseTemplate))
template.Must(tmpl.Parse(specificTemplate))
tmpl.ExecuteTemplate(os.Stdout, "base", nil)
}
Advanced Rendering Strategies
flowchart TD
A[Advanced Techniques] --> B[Template Composition]
A --> C[Custom Functions]
A --> D[Template Pipelines]
A --> E[Context-Aware Rendering]
Custom Function Techniques
func createAdvancedTemplate() *template.Template {
funcMap := template.FuncMap{
"safe": func(s string) template.HTML {
return template.HTML(s)
},
"transform": func(input string) string {
// Complex transformation logic
return strings.ToUpper(input)
},
}
return template.Must(template.New("advanced").Funcs(funcMap).Parse(
"Processed: {{.Input | transform}}"
))
}
Template Pipeline Techniques
Technique |
Description |
Example |
Chaining |
Multiple transformations |
{{.Value | func1 | func2}} |
Conditional Piping |
Conditional transformations |
{{if .Condition}}{{.Value | func}}{{end}} |
Complex Transformations |
Multi-step processing |
{{.Value | validate | sanitize | format}} |
Context-Aware Template Rendering
type RenderContext struct {
User string
Permissions map[string]bool
Environment string
}
func renderWithContext(ctx RenderContext) {
tmpl := template.Must(template.New("context").Parse(`
{{if .Permissions.canView}}
Welcome, {{.User}}!
Environment: {{.Environment}}
{{else}}
Access Denied
{{end}}
`))
tmpl.Execute(os.Stdout, ctx)
}
func optimizedTemplateRendering() {
// Template pool for reuse
templatePool := &sync.Pool{
New: func() interface{} {
return template.Must(template.New("pool").Parse("{{.Content}}"))
},
}
// Acquire and release template from pool
tmpl := templatePool.Get().(*template.Template)
defer templatePool.Put(tmpl)
}
Security Considerations
- Use
html/template
for web contexts
- Implement input sanitization
- Validate template functions
- Limit template execution time
- Use context with timeouts
Advanced Error Handling
func advancedErrorHandling(tmpl *template.Template, data interface{}) error {
var buf bytes.Buffer
if err := tmpl.Execute(&buf, data); err != nil {
// Detailed error logging
log.Printf("Template rendering error: %v", err)
return err
}
return nil
}
Best Practices for Advanced Templating
- Modularize template logic
- Use template inheritance
- Implement robust error handling
- Optimize template performance
- Ensure security through careful design
Advanced template techniques in Go provide powerful mechanisms for creating flexible, dynamic, and secure content generation solutions, enabling developers to build sophisticated rendering systems with ease.