Askama Review, Best Practices & Capstone Project

Learning Objectives: By the end of this lesson, you will be able to:

  • Review and apply all core Askama concepts
  • Follow best practices for template organization and safety
  • Build a small project using Askama, either as a web app or CLI tool

1. Welcome and Introduction (5 minutes)

Icebreaker Activity

What was the most surprising thing you learned about Askama? How has compile-time template checking changed your view of web development in Rust?

Lesson Overview

  • Duration: 90-120 minutes
  • Prerequisites: All previous Askama lessons
  • Materials Needed:
    • Rust toolchain
    • Code editor
    • Askama project (web or CLI)

2. Learning Objectives and Session Outline (5 minutes)

What We’ll Cover Today:

  1. Review of core Askama concepts
  2. Best practices for template-driven Rust projects
  3. Capstone mini-project (web or CLI)
  4. Troubleshooting and code review
  5. Next steps and further resources

Success Criteria:

By the end of this session, you should be able to design, implement, and review a small project using Askama, following best practices.

3. Foundation Knowledge (15-20 minutes)

Core Concepts Review

  • Template Structs: How to define and use them
  • Template Syntax: Expressions, control flow, filters, inheritance, includes, macros
  • Custom Filters: When and how to use them
  • Error Handling: Using Result from render()
  • Web Integration: Serving templates with Axum or another framework

Why This Matters:

  • Ensures your code is safe, maintainable, and production-ready
  • Reduces runtime errors and improves developer experience

Key Terminology

  • DRY: Don’t Repeat Yourself—reuse templates and macros
  • Type Safety: Rust and Askama check your data at compile time
  • Presentation Logic: Keep templates focused on display, not business logic

4. Best Practices and Professional Tips (15-20 minutes)

Template Organization

  • Store all templates in a templates/ directory
  • Use clear, consistent naming for files and blocks
  • Separate partials (e.g., _header.html) and macros (e.g., macros.html)

Code Structure

  • Keep complex logic in Rust, not in templates
  • Use template inheritance for layouts, includes for components, macros for repeated UI
  • Be explicit with types in structs and macro arguments

Compile-Time Safety

  • Leverage Askama’s compile-time checks to catch errors early
  • Test templates with different data shapes (empty, missing, etc.)

When to Use Askama

  • Server-side HTML rendering in Rust web apps
  • Generating reports, emails, or documentation from Rust

5. Capstone Mini-Project (40-60 minutes)

Project Options

Choose one of the following based on your interests:

Option 1: Web Application (with Axum)

Objective: Build a simple web app with 2-3 pages using Askama templates.

Requirements:

  • Use a base template with blocks for title and content
  • Create at least two child templates (e.g., home, about, items list)
  • Pass data from Axum handlers to templates
  • Use includes and macros for reusable UI
  • Serve static files (CSS) if desired

Starter Code: Add askama = "0.16", askama_web = { version = "0.16", features = ["axum-0.8"] }, axum = "0.8", and Tokio 1 with full features to [dependencies]. Create templates/home.html before compiling.

// main.rs
use askama::Template;
use askama_web::WebTemplate;
use axum::{Router, routing::get};

#[derive(Template, WebTemplate)]
#[template(path = "home.html")]
struct HomeTemplate {
    user: String,
}

async fn home() -> HomeTemplate {
    HomeTemplate { user: "Alice".to_string() }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(home));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

templates/home.html can start as {% extends "base.html" %}{% block content %}Hello, {{ user }}!{% endblock %}; also create templates/base.html with a content block (see Day 3). Add an about page and reusable components to meet the full capstone requirements.

Option 2: CLI HTML Report Generator

Objective: Build a command-line tool that generates an HTML report from input data.

Requirements:

  • Define a template struct for the report
  • Read data from a file or user input (the starter below uses hard-coded example data; add input handling as part of the project)
  • Render the report to an HTML file
  • Use loops, conditionals, and filters in the template

Starter Code:

use askama::Template;

#[derive(Template)]
#[template(path = "report.html")]
struct ReportTemplate {
    title: String,
    items: Vec<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let report = ReportTemplate {
        title: "My Report".to_string(),
        items: vec!["Item 1".into(), "Item 2".into()],
    };
    let html = report.render()?;
    std::fs::write("report.html", html)?;
    Ok(())
}

Create templates/report.html with, for example, <h1>{{ title }}</h1><ul>{% for item in items %}<li>{{ item|upper }}</li>{% else %}<li>No items</li>{% endfor %}</ul> to exercise loops, the loop’s empty-case {% else %}, and a filter. Add an {% if %} for an explicit conditional.

Project Steps

  1. Plan your data structures and templates
  2. Implement the Rust code and templates
  3. Test with different data
  4. Review for best practices

Extension Ideas

  • Add a custom filter or macro
  • Add navigation or styling
  • Handle errors gracefully

6. Troubleshooting and Code Review (10-15 minutes)

Common Pitfalls

  1. Problem: Template not found or wrong path Solution: Check file location and #[template(path = ...)]
  2. Problem: Field mismatch between struct and template Solution: Ensure names and types match
  3. Problem: Logic in templates Solution: Move complex logic to Rust code

Debugging Tips

  • Use cargo build to catch template errors
  • Read error messages carefully
  • Test with edge cases (empty lists, missing data)

7. Next Steps in Your Learning Journey (5 minutes)

  • Explore advanced Askama features (custom filters, macros)
  • Integrate with more complex web frameworks
  • Contribute to the Askama project or write your own filters/macros
  • Read the Askama Book and documentation

8. Summary and Review (5 minutes)

Key Takeaways

  1. Askama enables safe, maintainable, and fast template-driven Rust projects
  2. Best practices help you avoid common pitfalls and write production-ready code
  3. Capstone projects consolidate your learning and prepare you for real-world use

Quick Review Questions

  1. What are the benefits of compile-time template checking?
  2. How do you organize templates for a large project?
  3. What should you avoid putting in your templates?

For Instructors

Teaching Tips

  • Encourage students to plan before coding
  • Review code for DRYness, safety, and organization
  • Use peer review for project feedback

Assessment Ideas

  • Grade projects on functionality, code quality, and template organization
  • Use quizzes on best practices and troubleshooting
  • Have students present their projects and explain design choices

Adaptation Notes

  • For beginners: provide more scaffolding and template examples
  • For advanced students: challenge with more complex data and custom filters/macros
  • Online: use screen sharing and collaborative review for projects