macro_rules! html {
($($x:tt)*) => { ... };
}
Expand description
Generates an HTML string using the inputted syntax
§Creating a Text Element
§Using a String Literal
html!(div (style = "border: 1px solid black;" class = "Hello") "Hello World");
Will create the following string of HTML that consists of a div
with a style
attribute that creates a black border, a class
attribute set to Hello
and text set to "Hello World"
"<div style=\"border: 1px solid black;\" class=\"Hello\">Hello World</div>"
This renders as follows in the browser:
The first token (here div
) specifies the name of the element.
The set of parentheses ()
contains the attributes for the element. The attribute name comes before the =
and the attribute value after and is in double quotation marks. Different attributes are separated by whitespace.
The text in double quotation marks at the end of the content specifies the text content "Hello World"
.
§Using a Variable
The text can also be derived from a variable. In this case surround the variable with curly brackets {}
let example_text = "Hello World";
html!(div (style = "border: 1px solid black;" class = "Hello") {example_text});
gives the same result as before:
"<div style=\"border: 1px solid black;\" class=\"Hello\">Hello World</div>"
§Creating an Element with No Attributes or Content
Both html!(div)
and html!(div ())
will create a string of HTML consisting of an empty div with no styling
"<div></div>"
Void elements should not have end tags and this is handled accordingly. For example html!(hr)
will return "<hr />"
§Creating Elements that Contain other Elements
html!(ul () [el!(li () "First Sibling")] [el!(li () "Second Sibling")])
Will create the following string of HTML that consists of an unordered list with two items
"<ul><li>First Sibling</li><li>Second Sibling</li></ul>"
In the browser this renders as
- First Sibling
- Second Sibling
Each child component is surrounded by square brackets []
and is inputted into the macro el!
which creates the component. Multiple specified child components are treated as siblings.
The result from el!(li () "Second Sibling")
could have been stored in a variable and the variable used instead as follows:
let second_sibling = el!(li () "Second Sibling");
let result = html!(ul()[el!(li () "First Sibling")][second_sibling]);
This would return the same HTML String.
§Where Child Elements are Specified through a Vector or an Array
let example_list = [
el!(li () "First Sibling"),
el!(li () "Second Sibling")
];
html!(ul () vec[example_list])
Will create the following string of HTML that consists of an unordered list with two items
"<ul><li>First Sibling</li><li>Second Sibling</li></ul>"
In the browser this renders as
- First Sibling
- Second Sibling
Inserting the text vec
before the square brackets []
tells the macro to expect a vector or array.