8 releases (5 breaking)
0.6.1 | Jul 9, 2024 |
---|---|
0.6.0 |
|
0.5.0 | Jun 11, 2024 |
0.4.1 | May 23, 2024 |
0.1.0 | May 8, 2024 |
#122 in Template engine
707 downloads per month
11KB
118 lines
fhtml
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 likeDefault
. -
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 returnsfhtml::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
~240–690KB
~16K SLoC