[][src]Module ructe::Template_syntax

This module describes the template syntax used by ructe.

The syntax is inspired by Twirl, the Scala-based template engine in Play framework, but of course with rust types expressions instead of scala.

A template consists of three basic parts: First a preamble of use statements, each prepended by an @ sign. Secondly a declaration of the parameters the template takes. And third, the template body.

@(name: &str, value: &u32)

<html>
  <head><title>@name</title></head>
  <body>
    <p>The value of @name is @value.</p>
  <body>
</html>

As seen above, string slices and integers can easily be outputed in the template body, using @name where name is a parameter of the template. Actually, more complex expressions can be outputed in the same way, as long as the resulting value implements ToHtml. Rust types that implements Display automatically implements ToHtml in such a way that contents are safely escaped for html.

@use any::rust::Type;

@(name: &str, items: &[Type])

<html>
  <head><title>@name</title></head>
  <body>
    @if items.is_empty() {
      <p>There are no items.</p>
    } else {
      <p>There are @items.len() items.</p>
      <ul>
      @for item in items {
        <li>@item</li>
      }
      </ul>
  <body>
</html>

The curly brackets, { and }, is used for blocks (see Loops, Conditionals, and Calling other templates below). To use verbatim curly brackets in the template body, they must be escaped as @{ and @}, the same goes for the @ sign, that precedes expressions and special blocks; verbtim @ signs must be escaped as @@.

Modules

a_Value_expressions

A value expression can be as simple as @name to get the value of a parameter, but more complicated expressions, including function calls, are also allowed.

b_Loops

A ructe @for loop works just as a rust for loop, iterating over anything that implements std::iter::IntoIterator, such as a Vec or a slice.

c_Conditionals

Both @if statements with boolean expressions and match-like guard @if let statements are supported.

d_Calling_other_templates

The ability to call other templates for from a template makes both "tag libraries" and "base templates" possible with the same syntax.