Home
Head's Up: I'm in the middle of upgrading my site. Most things are in place, but there are something missing and/or broken including image alt text. Please bear with me while I'm getting things fixed.

Use Rust Struct Functions In A Sailfish Template

I'm working on the template engine for my static site generator. I've been using Minijinga. The base site builds in 2 seconds. Pretty good for 2K files. I'm curious to see if I can make it go faster. My next step is to experiment with Sailfish.

A critical factor for me is being able to call functions on the structs that are being used to render. That took a while to figure out in Minijinja. This is how I'm doing it in Sailfish :

Cargo.toml

[dependencies]
sailfish = "0.8.0"

templates/hello.stpl

<html>
  <body>
  <h2>Direct Key Access To Vec</h2>
  <% for msg in &messages { %>
    <div><%= msg %></div>
  <% } %>
  <h2>Function With Single String</h2>
    <div><%= h.ping() %></div>
  <h2>Function With Vec</h2>
  <% for item in h.runner() {%>
    <div><%= item %></div>
  <% } %>
  </body>
</html>

src/main.rs

use sailfish::TemplateOnce;

#[derive(TemplateOnce)]
#[template(path = "hello.stpl")]
struct HelloTemplate {
    messages: Vec<String>,
    h: Holder,
}

struct Holder {}

impl Holder {
    pub fn ping(&self) -> String {
        "one ping only".to_string()
    }
    pub fn runner(&self) -> Vec<String> {
        vec![
            "alfa".to_string(),
            "bravo".to_string(),
            "charlie".to_string(),
            "delta".to_string(),
        ]
    }
}

fn main() {
    let ctx = HelloTemplate {
        messages: vec![String::from("foo"), String::from("bar")],
        h: Holder {},
    };
    println!("{}", ctx.render_once().unwrap());
}

- I really don't need the build to go any faster. The first build goes in 2 seconds and individual page updates after that are virtually instant. This is really more about experimenting with things. I'm hoping the overall experience turns out to be a little easier than working with Minijinja

- I tried this without the child struct. It worked if there were not methods added via [TODO: Code shorthand span ] but as soon as I added one there it would throw errors about things getting borrowed.

- I don't see any methods for calling functions listed in the docs

- The docs do mention evaluating Rust expressions

- Seems that sending things in like this works fine

Footnotes And References