Crate ructe [] [src]

Rust Compiled Templates is a HTML template system for Rust.

Templates in a syntax inspired by Twirl, the Scala-based template engine in Play framework are translated to Rust language source code, to be compiled together with your program. The template syntax is currently documented only in the readme of the github repository for ructe.

How to use ructe

Ructe compiles your templates to rust code that should be compiled with your other rust code, so it needs to be called before compiling. Assuming you use cargo, it can be done like this:

First, specify a build script and ructe as a build dependency in Cargo.toml:

build = "src/build.rs"

[build-dependencies]
ructe = "^0.2"

Then, in the build script, compile all templates found in the templates directory and put the output where cargo tells it to:

extern crate ructe;

use ructe::compile_templates;
use std::env;
use std::path::PathBuf;

fn main() {
    let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap());
    let in_dir = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap())
        .join("templates");
    compile_templates(&in_dir, &out_dir).expect("compile templates");
}

And finally, include and use the generated code in your code. The file templates.rs will contain mod templates { ... }, so I just include it in my main.rs:

include!(concat!(env!("OUT_DIR"), "/templates.rs"));

When calling a template, the arguments declared in the template will be prepended by a Write argument to write the output to. It can be a Vec<u8> as a buffer or for testing, or an actual output destination. The return value of a template is std::io::Result<()>, which should be Ok(()) unless writing to the destination fails.

#[test]
fn test_hello() {
    let mut buf = Vec::new();
    templates::hello(&mut buf, "World").unwrap();
    assert_eq!(buf, b"<h1>Hello World!</h1>\n");
}

Modules

templates

The module containing your generated template code will also contain everything from here.

Functions

compile_static_files

Create a statics module inside outdir, containing static file data for all files in indir.

compile_templates

Create a templates module in outdir containing rust code for all templates found in indir.