Template Engine
Azu's template engine is built on top of Crinja, a Jinja2-compatible templating engine for Crystal. It provides powerful server-side rendering capabilities with type-safe data binding and automatic escaping.
Overview
The template engine provides:
Jinja2-compatible syntax for familiar templating
Type-safe data binding with compile-time validation
Automatic escaping for security
Template inheritance and includes
Custom filters and functions for data transformation
Basic Usage
Template Rendering
struct UserProfileResponse
include Response
include Templates::Renderable
def initialize(@user : User)
end
def render
view "user_profile.html", {
user: @user,
is_admin: @user.admin?,
posts: @user.recent_posts
}
end
endTemplate File (user_profile.html)
user_profile.html)Template Syntax
Variables
Variables are accessed using double curly braces:
Control Structures
If Statements
For Loops
While Loops
Template Inheritance
Base Template (base.html)
base.html)Child Template
Template Includes
Include Template (user_card.html)
user_card.html)Using Include
Filters
Built-in Filters
String Filters
Number Filters
Date Filters
Array Filters
Custom Filters
Registering Custom Filters
Using Custom Filters
Functions
Built-in Functions
Custom Functions
Registering Custom Functions
Using Custom Functions
Configuration
Template Configuration
Environment-Specific Configuration
Security
Automatic Escaping
The template engine automatically escapes output to prevent XSS attacks:
CSRF Protection
Performance
Template Caching
Fragment Caching
Template Precompilation
Error Handling
Template Error Handling
Template Debugging
Best Practices
1. Template Organization
Use logical directory structure
Keep templates focused and single-purpose
Use template inheritance for consistent layouts
Organize includes and macros in separate files
2. Performance
Cache frequently used templates
Use fragment caching for expensive parts
Minimize database queries in templates
Precompile templates in production
3. Security
Never trust user input
Use automatic escaping
Validate all template data
Use CSRF protection for forms
4. Maintainability
Use descriptive variable names
Keep templates simple and readable
Document complex template logic
Use consistent naming conventions
Next Steps
Markup DSL - Build components with Crystal code
Hot Reloading - Development workflow
Template Examples - Working examples
Ready to build templates? Start with the basic syntax examples above, then explore the Markup DSL for component-based development.
Last updated
Was this helpful?
