Templates

Azu includes a powerful template engine based on Jinja2 that provides server-side rendering, hot reloading, and a markup DSL for building dynamic web applications.

What are Templates?

Templates in Azu allow you to:

  • Generate HTML: Create dynamic HTML pages

  • Variable Interpolation: Insert data into templates

  • Control Structures: Use loops, conditionals, and inheritance

  • Hot Reloading: Automatic template reloading in development

  • Markup DSL: Programmatic HTML generation

Template Engine

Azu uses Crinja, a Jinja2-compatible template engine for Crystal:

Basic Template

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>{{ title }}</title>
  </head>
  <body>
    <h1>{{ title }}</h1>
    <p>Welcome, {{ user.name }}!</p>
  </body>
</html>

Template Variables

Pass data to templates:

Template Syntax

Variable Interpolation

Control Structures

Conditionals

Loops

Loop Variables

Template Inheritance

Base Template

Child Template

Template Includes

Markup DSL

Azu provides a programmatic markup DSL for generating HTML:

Basic Markup

Nested Elements

Attributes

Loops and Conditionals

Template Configuration

Configure templates in your application:

Custom Filters

Create custom template filters:

Using Custom Filters

Template Helpers

Create helper methods for templates:

Using Helpers in Templates

Hot Reloading

Enable hot reloading in development:

Hot Reloading Features

  • Automatic Reloading: Templates reload automatically when changed

  • File Watching: Monitors template directories for changes

  • Development Only: Only enabled in development environment

  • Performance: Minimal overhead in production

Template Caching

Cache templates for better performance:

Caching Strategies

  • Memory Caching: Templates cached in memory

  • File Caching: Compiled templates cached to disk

  • LRU Eviction: Least recently used templates evicted

  • TTL Expiration: Templates expire after specified time

Template Testing

Test your templates:

Best Practices

1. Use Template Inheritance

2. Keep Templates Simple

3. Use Includes for Reusable Components

4. Escape User Data

5. Use Meaningful Variable Names

Performance Considerations

1. Template Caching

2. Minimize Template Complexity

3. Use Includes Sparingly

Next Steps

Now that you understand templates:

  1. Components - Build interactive UI components

  2. WebSockets - Add real-time features

  3. Caching - Implement template caching

  4. Testing - Test your templates

  5. Performance - Optimize template performance


Templates in Azu provide a powerful way to generate dynamic HTML content. With Jinja2-compatible syntax, hot reloading, and a markup DSL, they make building web applications efficient and maintainable.

Last updated

Was this helpful?