Skip to main content

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:

  1. Define an audit level in your route definition
  2. Access this audit level in your templates
  3. Apply different template logic based on the audit level

Adding Custom Context

Basic Usage

To add custom context, follow these steps:

  1. Add a TemplateContext annotation to your route
  2. 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:

after.operation.extension.hbs
{{#if TemplateContext.AUDIT}}
if (opError != nil) {
println("Operation '{{{{OperationId}}}}' with audit level {{{{TemplateContext.AUDIT.Options.level}}}} failed, err: ", opError.Error())
}
{{/if}}

This example:

  1. Checks if audit context exists
  2. If present and an error occurs, prints:
    • The operation ID
    • The audit level
    • The error message