8 releases (5 breaking)

new 0.6.1 Jul 9, 2024
0.6.0 Jul 5, 2024
0.5.0 Jun 11, 2024
0.4.1 May 23, 2024
0.1.0 May 8, 2024

#139 in Template engine

Download history 83/week @ 2024-05-02 313/week @ 2024-05-09 151/week @ 2024-05-16 232/week @ 2024-05-23 1/week @ 2024-05-30 123/week @ 2024-06-06 33/week @ 2024-06-13 4/week @ 2024-06-20

160 downloads per month

MIT license

11KB
118 lines

fhtml

github crates.io docs.rs build status

fhtml provides convenient macros to write formatted HTML in Rust with embedded expressions.


Components

Components can be written in a number of ways, but the common ways to create reusable components include:

  • Function components — A function component can be a simple function that accepts some arguments and returns the computed HTML. These are the most common types of components across web frameworks. For fhtml, function components are not always the best way to create a component, since unlike most JSX frameworks, function components do not get special treatment when used inside an fhtml macro.

  • Struct components — A struct that implements Display is arguably the most JSX-like way to use components, since you can specify fields or "props" in an arbitrary order, and use convenient traits like Default.

  • Macros — In Rust 1.71, flattening of nested format_args! was introduced, but this only works if macros are invoked, not functions nor methods, even if they are inlined. So for smaller components, using a macro that returns fhtml::format_args! is the most efficient kind of component, since they are usually zero-cost.


Nested formatting

You often need to do additional formatting inside your HTML, and you might be tempted to use the standard format! for that. However, this is not the most efficient way of doing additional formatting. Instead, format_args! should be used in most cases. The overhead of format_args! is typically zero-cost since nested format_args! calls are flattened by the compiler.

let puppy_kind = "Golden Retriever";
fhtml::format! {
    <img
        alt={format_args!("A happy {} playing", puppy_kind)}
        src="puppy.jpg"
    />
}
// Is equivalent to writing:
std::format!("<img alt=\"A happy {} playing\" src=\"puppy.jpg\">", puppy_kind)

Const formatting

There are often situations when you want to write some HTML without using any runtime values or variables. For this, you can use fhtml::concat!.

const MY_PAGE: &str = fhtml::concat! {
    <!DOCTYPE html>
    <head>
        <title>"My HTML Page"</title>
    </head>
    <body>
        <h1>"Welcome to my HTML page!"</h1>
        {include_str!("../my-page.html")}
    </body>
}

Escaping

Values are not escaped automatically. fhtml exports a simple escape function. For more complex escaping, html-escape may be sufficient.

License

Licensed under MIT license.

Dependencies

~270–720KB
~17K SLoC