RsHtml is a compile-time, type-safe, lightweight and flexible template engine for Rust, designed to seamlessly integrate Rust code within HTML templates. It allows developers to write dynamic templates with embedded Rust expressions and logic, making it easier to generate HTML content programmatically.
- Embeds Rust expressions and blocks directly into HTML templates using the
@prefix or HTML-like component syntax (e.g.,<Component/>). - Supports conditional rendering (
@if,@else), loops (@for), and pattern matching (@match). - Supports Rust code blocks (
@{}), various Rust expression syntaxes (e.g.,@expression,@(expression), and a broad range of other Rust syntax. - Provides helper functions (e.g.,
@time()). - Supports raw output with
@rawblocks and server-side comments with@* ... *@. - Generates
efficient Rust codefor template rendering at compile time. - See the documentation for a full list of features. You can also read the Medium article.
Please see the Editor Support section in the documentation.
<h1>Welcome to RsHtml</h1>
@if self.is_logged_in {
<p>Hello, @self.username!</p>
} else {
<p>Please log in to continue.</p>
}
<ul>
@for item in self.items {
<li>@item</li>
}
</ul>
@match self.count {
0 => <p>this is zero</p>,
1 => true,
2 => self.count,
3 => {
<p>this is @self.count</p>
@if self.my_var == "rshtml" {
<p>rshtml</p>
}
},
_ => <p>other</p>
}@{
let x = 42;
let y = x * 2;
println!("Debug: x = {}, y = {}", x, y);
}@* This is a comment and will not appear in the output *@@use "Component.rs.html" as Component
@use "Component.rs.html" @* take Component as name *@
<Component title="home" is_ok=true>
<p>child content</p>
</Component>To use RsHtml in your Rust project, add it as a dependency in your Cargo.toml:
[dependencies]
rshtml = "x.y.z"
# The default folder can be changed. This is the default setup:
[package.metadata.rshtml]
views = { path = "views", extract_file_on_debug = false }- Define your template in an HTML file (e.g., home.rs.html) in
viewsfolder. - Use the
RsHtmlderive macro to parse the template. - Render the template with render function.
By default, #[derive(RsHtml)] infers the template file path from the struct's name.
It converts StructNamePage to struct_name.rs.html.
You can override this with #[rshtml(path = "...")].
use rshtml::{RsHtml, traits::RsHtml};
#[derive(RsHtml)]
//#[rshtml(path = "about.rs.html", no_warn)] // The template location can be configured via the rshtml path parameter. RsHtml warnings can be disabled.
struct HomePage { // Looks for home.rs.html in views folder.
title: String,
}
fn main() {
let homepage = HomePage {
title: "Home Page".to_string()
};
let result = homepage.render().unwrap();
print!("{}", result);
}Contributions are welcome! Feel free to open issues or submit pull requests to improve RsHtml.