Skip to content

Getting Started

Prepare the template file

Create a new directory named templates in the same directory as Cargo.toml. Copy the following contents and paste it to a new file named templates/hello.stpl.

<html>
  <body>
    <% for msg in &messages { %>
      <div><%= msg %></div>
    <% } %>
  </body>
</html>

Now your project structure should be like this:

Cargo.toml
src/
    (Source files)
templates/
    hello.stpl

Render the template

  1. Import the sailfish crates:
use sailfish::TemplateOnce;
  1. Define the template struct to be rendered:
#[derive(TemplateOnce)]  // automatically implement `TemplateOnce` trait
#[template(path = "hello.stpl")]  // specify the path to template
struct HelloTemplate {
    // data to be passed to the template
    messages: Vec<String>,
}
  1. Render the data with render_once() method.
fn main() {
    let ctx = HelloTemplate {
        messages: vec![String::from("foo"), String::from("bar")],
    };

    // Now render templates with given data
    println!("{}", ctx.render_once().unwrap());
}

That's it!

You can find more examples in the example directory in the sailfish repository.