Custom Context
Gleece enhances your templating process by allowing you to add custom context fields. This feature is particularly useful when you need to:
- Add custom logic to your templates
- Include specific context from route definitions
- Implement conditional template behavior
Use Cases
A common use case is template extension for auditing. For instance, you might want to:
- Define an audit level in your route definition
- Access this audit level in your templates
- Apply different template logic based on the audit level
Adding Custom Context
Basic Usage
To add custom context, follow these steps:
- Add a
TemplateContext
annotation to your route - Set the desired value, attributes, and descriptions
Here's a simple example:
// @Method(GET)
// @Route(/custom-context-route)
// @TemplateContext(AUDIT, {level: "critical"}) The audit level description
func (ec *ExampleController) TemplateContextRoute() (string, error) {
return "", nil
}
Important Note
While you can add multiple TemplateContext
annotations to a route, each annotation must have a unique value (e.g., AUDIT
).
Understanding the Structure
Custom context is organized into a map structure where:
- Each
TemplateContext
annotation becomes an entry in the map - The annotation value (e.g.,
AUDIT
) serves as the key - The context details are stored in a structured format
Here's how the data is structured:
map[string]TemplateContext{
"AUDIT": {
Options: map[string]any{"level": "critical"},
Description: "The audit level description",
},
}
Using Custom Context in Templates
Accessing Context Data
When working with templates (either extended or overridden):
- Use the
TemplateContext
object to access custom fields - Each route context includes a
TemplateContext
map containing all custom contexts
Practical Example
Here's how to use custom context in an AfterOperationRoutesExtension
template to handle operation errors:
This example:
- Checks if audit context exists
- If present and an error occurs, prints:
- The operation ID
- The audit level
- The error message