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
end

ECR 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

  1. Keep Templates Simple: Avoid complex logic in templates

  2. Use Helper Methods: Move complex logic to helper classes

  3. Consistent Indentation: Maintain readable code structure

  4. Error Handling: Include proper error handling in templates

  5. Documentation: Add comments to explain complex template logic

Performance

  1. Template Caching: Cache frequently used templates

  2. Minimize File I/O: Load templates once and reuse

  3. Efficient Loops: Use appropriate iteration methods

  4. Memory Management: Clean up template cache when needed

Maintainability

  1. Consistent Naming: Use consistent naming conventions

  2. Modular Design: Break complex templates into smaller parts

  3. Version Control: Track template changes in version control

  4. Testing: Test template rendering with various inputs

Last updated