Skip to main content

Crate rshtml

Crate rshtml 

Source
Expand description

Crates.io Version GitHub Repository Docs.rs Documentation Full Documentation

§RsHtml: A Template Engine for Seamless HTML and Rust Integration.

RsHtml is a powerful template engine that transforms your HTML templates into highly efficient Rust code at compile time, allowing you to seamlessly use Rust logic and expressions together with HTML to harness the full power of Rust for dynamic content generation. It is designed to help you build flexible and maintainable web applications.

Demo

§Quick Start

Add to Cargo.toml:

[dependencies]
rshtml = "0.6.0" # Use the latest version

v! macro, to write HTML within Rust:

use rshtml::{View, v};
use std::fmt;

fn main() -> fmt::Result {
  let template = "RsHtml";
  let hello = v!(<p>Hello {template}</p>);

  let mut out = String::with_capacity(hello.text_size());

  hello.render(&mut out)?;

  print!("{out}");

  Ok(())
}

For the .rs.html file:

use rshtml::View;

// The `path` parameter specifies a path relative to `CARGO_MANIFEST_DIR` or the
// current working directory. The `extract` parameter extracts the Rust segments from
// the `.rs.html` file into a separate file and includes it, thereby simplifying error handling.
#[derive(View)]
// #[view(path = "views/home.rs.html", extract)] // These are optional.
struct HomePage { // Looks for views/home.rs.html in views folder.
    title: String,
}


fn main() {
   let homepage = HomePage {
       title: "Home Page".to_string()
   };

    let mut out = String::with_capacity(homepage.text_size());
    homepage.render(&mut out).unwrap();

    print!("{}", out);
}

The View macro implements the View trait for the struct, making it usable with the v! macro.

Macros§

v
Enables writing HTML within Rust and allows for embedding Rust code using the {} syntax. The evaluated result is inserted into the output and must implement the View or Display trait.

Structs§

EscapingWriter
Exp
TextSize
ViewFn
ViewIter
Allows iterators to be rendered inside the v macro without the need to call collect.

Traits§

IntoViewIter
Render
View
The View trait makes implementing structs renderable and usable within other views.
Write
To render a View, the render function requires a type that implements the Write trait. This Write trait mandates the implementation of fmt::Write. Standard library types implementing fmt::Write also implement the Write trait via RsHtml.

Derive Macros§

View
The primary derive macro for enabling RsHtml templating on a struct.