Render HTML Templates

This guide shows you how to render HTML templates using Azu's Crinja template engine.

Basic Template Rendering

Create an endpoint that renders a template:

struct HomeEndpoint
  include Azu::Endpoint(EmptyRequest, Azu::Response::Html)
  include Azu::Templates::Renderable

  get "/"

  def call
    view "home/index.html", {
      title: "Welcome",
      message: "Hello, World!"
    }
  end
end

Template Location

Templates are stored in the views directory by default:

Template Syntax

Crinja uses Jinja2-style syntax:

Variables

Pass data to templates:

Access in template:

Loops

Iterate over collections:

Loop variables:

  • loop.index - Current iteration (1-indexed)

  • loop.index0 - Current iteration (0-indexed)

  • loop.first - True on first iteration

  • loop.last - True on last iteration

  • loop.length - Total number of items

Conditionals

Filters

Transform values with filters:

Layouts

Create a base layout:

Extend the layout:

Partials

Include reusable components:

Use the partial:

Macros

Define reusable template functions:

Comments

Raw Output

Disable template processing:

Custom Helpers

Add custom template functions:

Use in template:

See Also

Last updated

Was this helpful?