Template Engine (ECR)
Azu CLI uses Crystal's ECR (Embedded Crystal) as its template engine for code generation. ECR provides a powerful, type-safe way to embed Crystal code within templates, enabling dynamic content generation while maintaining compile-time safety.
Overview
ECR (Embedded Crystal) is Crystal's built-in template engine that allows you to embed Crystal code directly within text templates. It provides:
Type Safety: Compile-time checking of embedded Crystal code
Performance: Templates are compiled to native code, not interpreted
Simplicity: Familiar Crystal syntax within templates
Flexibility: Full access to Crystal's language features
Integration: Seamless integration with Crystal's compilation process
ECR Basics
Template Structure
ECR templates consist of text content with embedded Crystal code:
# Basic ECR template
class <%= @name_camelcase %> < CQL::Model
table :<%= @name_underscore.pluralize %>
<% @attributes.each do |attr| %>
column :<%= attr.name %>, <%= attr.column_type %>
<% end %>
timestamps
endECR Tags
ECR uses specific tags to embed Crystal code:
Template Rendering
Templates are rendered using the ECR.render method:
Template Variables
Context Object
Templates receive a context object with variables:
Variable Types
Templates can work with various data types:
Template Organization
Directory Structure
Templates are organized by generator type and purpose:
Template Naming Conventions
Templates follow consistent naming patterns:
Template Examples
Model Template
Endpoint Template
Service Template
Component Template
Jinja Template
Advanced ECR Features
Conditional Logic
Loops and Iteration
Method Calls
Error Handling
Template Helpers
String Manipulation
Custom Helpers
Template Caching
Performance Optimization
Template Validation
Template Customization
User Customization
Users can override default templates by creating custom template files:
Template Inheritance
Templates can inherit from base templates:
Best Practices
Template Design
Keep Templates Simple: Avoid complex logic in templates
Use Helper Methods: Move complex logic to helper classes
Consistent Indentation: Maintain readable code structure
Error Handling: Include proper error handling in templates
Documentation: Add comments to explain complex template logic
Performance
Template Caching: Cache frequently used templates
Minimize File I/O: Load templates once and reuse
Efficient Loops: Use appropriate iteration methods
Memory Management: Clean up template cache when needed
Maintainability
Consistent Naming: Use consistent naming conventions
Modular Design: Break complex templates into smaller parts
Version Control: Track template changes in version control
Testing: Test template rendering with various inputs
Related Documentation
Generator System - Code generation architecture
CLI Framework (Topia) - Command-line interface framework
Commands Reference - Generate command documentation
Template Variables - Template variable reference
Last updated