Crate build_html
source ·Expand description
This library is designed to provide a simple way to generate HTML documents from within Rust
code. To generate documents, this library uses the builder pattern; calls to add elements are
repeatedly chained together to dynamically build up an HTML document. The document is then
flushed to an HTML string which can be used elsewhere in your program with
to_html_string()
Use
Everything you need to use this crate has been exported from the crate root. This means that
you can get easy access to every element using the import: use build_html::*
.
If compatibility is important, or you don’t need access to every element, you can also import
elements piecemeal and prefix types with the package name. Note that the traits HTML
and
HtmlContainer
must be in scope for the library to be useful:
use build_html::{self, Html, HtmlContainer};
let page = build_html::HtmlPage::new()
.with_paragraph("Some Text")
.to_html_string();
Once the package is imported, the HtmlPage
struct will provide the base for most use cases.
This struct provides the boilerplate for an HTML5 page, and allows content to be added to it
using chained methods.
Example
use build_html::*;
let html: String = HtmlPage::new()
.with_title("My Page")
.with_header(1, "Main Content:")
.with_container(
Container::new(ContainerType::Article)
.with_attributes([("id", "article1")])
.with_header_attr(2, "Hello, World", [("id", "article-head")])
.with_paragraph("This is a simple HTML demo")
)
.to_html_string();
produces a string equivalent to:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1>Main Content:</h1>
<article id="article1">
<h2 id="article-head">Hello World</h2>
<p>This is a simple HTML demo</p>
</article>
</body>
</html>
Extensibility
The majority of the add_x
methods specified in HtmlContainer
are defined over generic
bounds. This means that they are quite flexibile, and you can pass in almost anything
implementing the ToString
trait.
In the event that you require additional tags or types not implemented in this library, you
can achieve this using one of two escape hatches. For a more structured approach, consider
seeing the documentation for HtmlContainer::add_html
. For more one-off situations, consider
HtmlContainer::add_raw
.
Structs
- A container for HTML elements.
- An entire page of HTML which can built up by chaining addition methods.
- Represents an HTML
<table>
element with all its children. - A single table cell
- A builder for more manual control over individual table elements
Enums
- The different types of HTML containers that can be added to the page
- Versions of the HTML (or XHTML) standard
- The different types of table cells
Traits
- An element that can be converted to an HTML string
- An HTML element that can contain other HTML elements
Functions
- Escape the provided string.