A statically-checked Rust Template Engine
boilerplate
boilerplate is a statically-checked Rust template engine with no runtime dependencies. There are two ways to use boilerplate, boilerplate::Boilerplate, a derive macro, and boilerplate::boilerplate, a function-like macro.
Derive Macro
Derive Boilerplate on the type you want to use as a template context:
use boilerplate::Boilerplate;
#[derive(Boilerplate)] struct MyTemplateTxt { foo: bool, bar: Result<String, Box<dyn std::error::Error>>, }
boilerplate template code and interpolations are Rust, so errors are checked at compile time and the template language is easy to learn:
%% if self.foo {
Foo was true!
%% }
%% match &self.bar {
%% Ok(ok) => {
Pretty good: {{ ok }}
%% }
%% Err(err) => {
Not so great: {{ err }}
%% }
%% }
The Boilerplate macro provides a Display implementation, so you can instantiate a template context and convert it to a string:
let rendered = MyTemplateTxt { foo: true, bar: Ok("hello".into()) }.to_string();
Or use it in a format string:
println!("The output is: {}", MyTemplateTxt { foo: false, bar: Err("hello".into()) });
boilerplate's implementation is exceedingly simple. Try using cargo-expand to expand the Boilerplate macro, inspect derived Display implementations, and debug template issues.
Function-like Macro
use boilerplate::boilerplate;
let foo = true; let bar: Result<&str, &str> = Ok("yassss");
let output = boilerplate!( "%% if foo { Foo was true! %% } %% match bar { %% Ok(ok) => { Pretty good: {{ ok }} %% } %% Err(err) => { Not so great: {{ err }} %% } %% } ");
assert_eq!(output, "Foo was true!\nPretty good: yassss\n");
Quick Start
Add boilerplate to your project's Cargo.toml:
[dependencies]
boilerplate = "*"
Create a template in templates/my-template.txt:
Foo is {{self.n}}!
Define, instantiate, and render the template context:
use boilerplate::Boilerplate;
#[derive(Boilerplate)] struct MyTemplateTxt { n: u32, }
asserteq!(MyTemplateTxt { n: 10 }.tostring(), "Foo is 10!\n");
Examples
See the docs for more information and examples.
Syntax Highlighting
This repository contains a Vim plugin for boilerplate syntax highlighting, in the vim subdirectory.
To install it with vim-plug:
Plug 'casey/boilerplate', { 'rtp': 'vim' }
Highlighting is enabled with the :Boilerplate command, rather than automatically, since boilerplate templates do not have a unique extension.
See :help boilerplate for more information.