Template Engine

Sprig Functions

Complete reference for Sprig functions available in Compozy templates

Compozy's template engine includes the full Sprig function library, providing powerful data transformation capabilities within your YAML templates. This reference covers the most commonly used functions organized by category.

Function Categories

String Functions

String functions handle text manipulation, formatting, and validation operations.

Basic string operations cover case conversion, trimming, and replacement:

# Case conversion
title: "{{ .user.name | title }}"                    # "john doe" → "John Doe"
upper: "{{ .status | upper }}"                       # "success" → "SUCCESS"  
lower: "{{ .env.NODE_ENV | lower }}"                 # "PRODUCTION" → "production"

# Trimming whitespace
cleaned: "{{ .input | trim }}"                       # "  hello  " → "hello"
trimPrefix: "{{ .filename | trimPrefix 'tmp_' }}"    # "tmp_file.txt" → "file.txt"
trimSuffix: "{{ .filename | trimSuffix '.txt' }}"    # "file.txt" → "file"

# String replacement
slug: "{{ .title | lower | replace ' ' '-' }}"       # "My Title" → "my-title"
sanitized: "{{ .input | replace '/' '_' }}"          # "path/to/file" → "path_to_file"

Common patterns: Chain functions for complex transformations, use consistent naming conventions.

Numeric Functions

Numeric functions handle mathematical operations, comparisons, and type conversions.

Arithmetic operations perform basic mathematical calculations:

# Basic math
sum: "{{ add 10 5 }}"                                # 15
difference: "{{ sub 10 5 }}"                         # 5
product: "{{ mul 10 5 }}"                            # 50
quotient: "{{ div 10 5 }}"                           # 2
remainder: "{{ mod 10 3 }}"                          # 1

# With template variables
total: "{{ add .price .tax }}"
percentage: "{{ div (mul .part 100) .total }}"
scaled: "{{ mul .value .scale_factor }}"

Use cases: Price calculations, percentage computations, data scaling.

Collection Functions

Collection functions operate on arrays and maps for data manipulation.

Array operations work with lists and sequences:

# Array properties
count: "{{ len .items }}"                             # Number of items
is_empty: "{{ empty .items }}"                        # true if empty array

# Element access
first_item: "{{ first .items }}"                      # First element
last_item: "{{ last .items }}"                        # Last element
rest_items: "{{ rest .items }}"                       # All except first
nth_item: "{{ index .items 2 }}"                      # Third element (0-indexed)

# Array membership
has_item: "{{ has .item .items }}"                    # Check if array contains item

Array patterns: Use consistent indexing, check bounds before access.

Date Functions

Date functions handle time formatting, arithmetic, and manipulation.

Current time functions provide various timestamp formats:

# Current timestamp
now_timestamp: "{{ now }}"                            # Current time object
unix_timestamp: "{{ now | unixEpoch }}"               # Unix timestamp
nano_timestamp: "{{ now | date_in_zone 'UTC' | date '2006-01-02T15:04:05.000000000Z' }}"

# Common formats
current_date: "{{ now | date '2006-01-02' }}"         # "2023-10-15"
current_time: "{{ now | date '15:04:05' }}"           # "14:30:25"
iso_format: "{{ now | date '2006-01-02T15:04:05Z' }}" # ISO 8601 format

Timezone handling: Use date_in_zone for specific timezone formatting.

Security Functions

Security functions provide XSS protection and safe escaping for different contexts.

HTML escaping prevents XSS in HTML content and attributes:

# HTML content escaping
user_message: "{{ .user_input | htmlEscape }}"
blog_content: "{{ .tasks.get_content.output.text | htmlEscape }}"

# Example transformations:
# Input: "<script>alert('XSS')</script>"
# Output: "&lt;script&gt;alert('XSS')&lt;/script&gt;"

# HTML attribute escaping
user_profile: |
  <div class="user-card" 
       data-name="{{ .user.name | htmlAttrEscape }}"
       title="{{ .user.bio | htmlAttrEscape }}">
    {{ .user.display_name | htmlEscape }}
  </div>

# Example transformations:
# Input: 'John" onclick="alert(\'XSS\')'
# Output: 'John&quot; onclick=&quot;alert(&#39;XSS&#39;)'

Context awareness: Use htmlEscape for content, htmlAttrEscape for attributes.

Encoding Functions

Encoding functions handle data serialization and format conversion.

JSON operations convert between objects and JSON strings:

# Convert to JSON
json_string: "{{ .data | toJson }}"                   # Convert object to JSON
pretty_json: "{{ .data | toPrettyJson }}"             # Pretty-printed JSON

# Parse JSON (use with caution)
parsed_data: "{{ .json_string | fromJson }}"          # Parse JSON string

# Common use cases
api_payload: "{{ .request_data | toJson }}"
config_dump: "{{ .config | toPrettyJson }}"

JSON safety: Validate JSON strings before parsing, handle parse errors gracefully.

Logical Functions

Logical functions provide conditional operations and flow control.

Boolean operations combine and test conditions:

# Boolean logic
both_true: "{{ and .condition1 .condition2 }}"       # Logical AND
either_true: "{{ or .condition1 .condition2 }}"      # Logical OR
negated: "{{ not .condition }}"                       # Logical NOT

# Complex expressions
valid_user: "{{ and .user.verified (not (empty .user.email)) }}"
should_process: "{{ or .force_process (and .auto_process (gt .priority 5)) }}"

Complex conditions: Use parentheses to control evaluation order.

Common Patterns

Real-world examples of function usage in typical scenarios.

Configuration management with environment-based settings:

# Environment-based configuration
database_url: "{{ .env.DATABASE_URL | default 'sqlite://local.db' }}"
debug_mode: "{{ .env.DEBUG | default 'false' | bool }}"
port: "{{ .env.PORT | default '3000' | int }}"

# Feature flags
feature_enabled: "{{ and .env.ENABLE_FEATURE (eq .env.ENVIRONMENT 'production') }}"
log_level: "{{ .env.LOG_LEVEL | default 'info' | lower }}"

Best practices: Provide sensible defaults, validate environment variables.

Performance Considerations

Understanding function performance helps optimize template rendering.

High-performance functions execute quickly:

# Fast operations (< 1μs)
fast_ops: |
  {{ .name | title }}                    # ~0.5μs
  {{ .text | trim }}                     # ~0.3μs
  {{ .status | upper }}                  # ~0.2μs
  {{ .value | default "none" }}          # ~0.4μs
  {{ len .items }}                       # ~0.1μs
  {{ add .a .b }}                        # ~0.1μs

Optimal usage: Prefer simple functions for frequently rendered templates.

References

Sprig functions provide the foundation for powerful template-based configurations in Compozy. Remember to prioritize security by always escaping user input and using appropriate functions for each context.