pub struct Element { /* private fields */ }Expand description
An HTML element: a tag name, attributes, optional text content, and children.
Every builder method takes self and returns Self, so they chain. Content and
attribute values are escaped as they go in, not when the element is rendered.
§Examples
use molt::prelude::*;
let card = div()
.add_class("card")
.set_id("hero")
.child(h1().text("Welcome"))
.child(p().text("Fuel, tyres & chain."));
assert_eq!(
card.render(),
r#"<div class="card" id="hero"><h1>Welcome</h1><p>Fuel, tyres & chain.</p></div>"#
);Implementations§
Source§impl Element
impl Element
Sourcepub fn from_static(tag: &'static str) -> Self
pub fn from_static(tag: &'static str) -> Self
Creates an element whose tag is a 'static string, without allocating it.
What the built-in constructors (div(), p(), …) use. Reach for it when you define
your own element helpers with a literal tag, such as a custom element.
§Examples
use molt::prelude::*;
assert_eq!(Element::from_static("my-card").text("hi").render(), "<my-card>hi</my-card>");Sourcepub fn attributes(&self) -> &[Attribute]
pub fn attributes(&self) -> &[Attribute]
The attributes, in insertion order.
Sourcepub fn is_self_closing(&self) -> bool
pub fn is_self_closing(&self) -> bool
Whether this element closes without an end tag, dropping content and children.
Void tags do this on their own. Self::self_closing opts any other tag into the
same shape.
§Examples
use molt::prelude::*;
assert!(!div().is_self_closing());
assert!(div().self_closing(true).is_self_closing());Sourcepub fn find(&self, tag: &str) -> Option<&Element>
pub fn find(&self, tag: &str) -> Option<&Element>
The first element below this one, in document order, with this tag.
For asserting on a tree in a test without searching its rendered string. The search
uses an explicit stack, so a deep tree cannot overflow it, and it borrows: nothing is
cloned. This element itself is not a match, only what is inside it, and tag is
compared as written ("div", not "DIV").
§Examples
use molt::prelude::*;
let page = div()
.child(nav().child(a().attr("href", "/docs").text("Docs")))
.child(a().attr("href", "/blog").text("Blog"));
let first = page.find("a").expect("a link");
assert_eq!(first.attribute("href"), Some("/docs"));
assert_eq!(first.render(), r#"<a href="/docs">Docs</a>"#);
assert!(page.find("table").is_none());Sourcepub fn find_all<'a>(
&'a self,
tag: &'a str,
) -> impl Iterator<Item = &'a Element> + 'a
pub fn find_all<'a>( &'a self, tag: &'a str, ) -> impl Iterator<Item = &'a Element> + 'a
Every element below this one with this tag, in document order. See Self::find.
§Examples
use molt::prelude::*;
let list = ul().children_from(["a", "b", "c"].map(|x| li().text(x)));
assert_eq!(list.find_all("li").count(), 3);
let last = list.find_all("li").last().expect("three items");
assert_eq!(last.render(), "<li>c</li>");Sourcepub fn attribute(&self, name: &str) -> Option<&str>
pub fn attribute(&self, name: &str) -> Option<&str>
The value of the first attribute with this name, as it is written into the markup.
The value was escaped when it was set, so attr("title", "a & b") reads back as
a & b. A boolean attribute reads as ""; use Self::attributes and
Attribute::is_boolean to tell it from an empty value. The name is compared as
written. The URL policy is applied at render time, so a URL that will be written as
# still reads as it was set.
§Examples
use molt::prelude::*;
let link = a().attr("href", "/docs?x=1&y=2").bool_attr("download");
assert_eq!(link.attribute("href"), Some("/docs?x=1&y=2"));
assert_eq!(link.attribute("download"), Some(""));
assert_eq!(link.attribute("target"), None);Sourcepub fn text(self, content: impl AsRef<str>) -> Self
pub fn text(self, content: impl AsRef<str>) -> Self
Appends text, escaping it, at the position of the call.
Text added before any child lands in the element’s content, which is the cheap
shape for a leaf (p().text("x") allocates no child list). Once the element has a
child, text becomes a text child instead, so the order of the calls is the order in the
markup: p().child(strong()).text("after") renders the text after the <strong>.
Calling it twice appends twice; it never replaces.
§Examples
use molt::prelude::*;
let line = p()
.text("Owner: ")
.child(strong().text("Ada"))
.text(" (admin)");
assert_eq!(line.render(), "<p>Owner: <strong>Ada</strong> (admin)</p>");Sourcepub fn raw_text(self, content: impl Into<String>) -> Self
pub fn raw_text(self, content: impl Into<String>) -> Self
Appends text without escaping it, at the position of the call.
The documented escape hatch for markup you already trust. <script> and <style>
use this by default. Position follows Self::text: content before the first child,
a raw child after it.
Do not put untrusted data in a <script> or <style> through this. The element
ends at the first </script (or </style) wherever it appears, including inside a
JSON string. For JSON data use seo::json_ld or
seo::script_json, which escape it; there is no safe way to
embed untrusted text in script code.
§Examples
use molt::prelude::*;
// The string is trusted markup written right here.
assert_eq!(p().raw_text("a & b").render(), "<p>a & b</p>");Sourcepub fn children_from<N: Into<Node>>(
self,
children: impl IntoIterator<Item = N>,
) -> Self
pub fn children_from<N: Into<Node>>( self, children: impl IntoIterator<Item = N>, ) -> Self
Appends several child nodes.
Sourcepub fn csp_hash(&self) -> Option<String>
pub fn csp_hash(&self) -> Option<String>
The CSP hash of this <script> or <style>: sha256- and the base64 SHA-256 of what
the browser reads between the tags. None for any other tag, and for a tag that is
self-closing.
A page with script-src 'self' and no 'unsafe-inline' still runs an inline script
whose hash is listed in the policy, and the same goes for style-src. Put the result
in single quotes there: script-src 'self' 'sha256-…'. Without the quotes it is also
the value of an integrity attribute.
The hash covers the content as it is written into the page: text set with
Self::text is hashed after escaping, and Self::raw_text as it is. The child
nodes are hashed as the compact render writes them, so for an element with children the
pretty render, which indents them, does not match. The usual element, a single text,
renders the same in both. Change one byte and the hash changes, which is the point.
§Examples
use molt::prelude::*;
// The script is code written right here, so `raw_text` is correct.
let theme = script().raw_text("document.documentElement.dataset.theme='dark';");
let hash = theme.csp_hash().expect("a script has a hash");
assert_eq!(hash, "sha256-IL7rwv2VOjU6vInkRwJTvFERJLVY80azmQFKaT/moJg=");
let policy = format!("script-src 'self' '{hash}'");
assert!(policy.starts_with("script-src 'self' 'sha256-"));
assert_eq!(div().csp_hash(), None);Sourcepub fn add_attribute(self, attribute: Attribute) -> Self
pub fn add_attribute(self, attribute: Attribute) -> Self
Appends an attribute. Does not deduplicate.
Sourcepub fn attr(self, key: impl Into<String>, value: impl AsRef<str>) -> Self
pub fn attr(self, key: impl Into<String>, value: impl AsRef<str>) -> Self
Appends key="value", escaping the value. Does not deduplicate.
Sourcepub fn bool_attr(self, key: impl Into<String>) -> Self
pub fn bool_attr(self, key: impl Into<String>) -> Self
Appends a boolean attribute, which renders as a bare key.
Sourcepub fn trusted_url(self, key: impl Into<String>, value: impl AsRef<str>) -> Self
pub fn trusted_url(self, key: impl Into<String>, value: impl AsRef<str>) -> Self
Replaces key with a URL that is written as given, even if it is a script URL.
The value is still attribute-escaped. Use this only for a URL you wrote yourself.
§Examples
use molt::prelude::*;
assert_eq!(
a().attr("href", "javascript:x")
.trusted_url("href", "javascript:print()")
.render(),
"<a href=\"javascript:print()\"></a>"
);Sourcepub fn self_closing(self, yes: bool) -> Self
pub fn self_closing(self, yes: bool) -> Self
Closes this element without an end tag, and does not render its content or children.
true emits > or, when RenderOptions::xhtml_self_closing is set, />, even
when the tag is not void. The default is false, so existing markup is unchanged.
Attributes are still written, which is what keeps the URL policy in front of a tag
that would otherwise have been emitted as raw markup.
§Examples
use molt::core::RenderOptions;
use molt::prelude::*;
let field = div().attr("id", "x").self_closing(true).child(span().text("no"));
assert_eq!(field.render(), "<div id=\"x\">");
assert_eq!(
field.render_with(&RenderOptions::compact().with_xhtml_self_closing(true)),
"<div id=\"x\" />"
);Sourcepub fn data_attr(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self
pub fn data_attr(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self
Appends data-{key}="{value}".
Sourcepub fn data_attrs<K: AsRef<str>, V: AsRef<str>>(
self,
data: impl IntoIterator<Item = (K, V)>,
) -> Self
pub fn data_attrs<K: AsRef<str>, V: AsRef<str>>( self, data: impl IntoIterator<Item = (K, V)>, ) -> Self
Appends several data-* attributes.
Takes an ordered iterator rather than a map: a hash map would render its attributes in a different order from one run to the next, and this makes the output stable.
Sourcepub fn aria_attr(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self
pub fn aria_attr(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self
Appends aria-{key}="{value}".
Sourcepub fn aria_attrs<K: AsRef<str>, V: AsRef<str>>(
self,
aria: impl IntoIterator<Item = (K, V)>,
) -> Self
pub fn aria_attrs<K: AsRef<str>, V: AsRef<str>>( self, aria: impl IntoIterator<Item = (K, V)>, ) -> Self
Appends several aria-* attributes, in the order given.
Sourcepub fn add_class(self, class_name: impl AsRef<str>) -> Self
pub fn add_class(self, class_name: impl AsRef<str>) -> Self
Appends a class name to class, space-joined.
Only the new value is escaped — the existing attribute is already escaped, and re-escaping it would double-encode, and a test pins exactly that.
Sourcepub fn add_classes<S: AsRef<str>>(
self,
class_names: impl IntoIterator<Item = S>,
) -> Self
pub fn add_classes<S: AsRef<str>>( self, class_names: impl IntoIterator<Item = S>, ) -> Self
Appends several class names.
Trait Implementations§
Source§impl Debug for Element
Writes the same text the derive did for a tree up to [DEBUG_MAX_DEPTH] levels deep, with
{:#?} for the multi-line form. Below that depth the children are written as ..., so
formatting a tree of any depth (a failing assert_eq! on one, say) cannot overflow the
stack. The text is for people, not a format to parse, and may change.
impl Debug for Element
Writes the same text the derive did for a tree up to [DEBUG_MAX_DEPTH] levels deep, with
{:#?} for the multi-line form. Below that depth the children are written as ..., so
formatting a tree of any depth (a failing assert_eq! on one, say) cannot overflow the
stack. The text is for people, not a format to parse, and may change.
§Examples
use molt::prelude::*;
let mut tree = p().text("bottom");
for _ in 0..100_000 {
tree = div().child(tree);
}
let shown = format!("{tree:?}");
assert!(shown.starts_with(r#"Element { tag: "div""#));
assert!(shown.contains("children: ..."));Source§impl Drop for Element
Tears the subtree down iteratively.
impl Drop for Element
Tears the subtree down iteratively.
The derived drop glue recurses once per nesting level, so a tree deep enough to need the iterative writer would abort while being freed instead — after rendering fine. Draining into an explicit worklist keeps teardown flat.
Each node has its children moved out before it goes out of scope, so the Drop that
runs for it finds nothing left to recurse into.
impl Eq for Element
Source§impl<N: Into<Node>> Extend<N> for Element
Appends nodes as children, so element.extend(items) works beside children_from.
impl<N: Into<Node>> Extend<N> for Element
Appends nodes as children, so element.extend(items) works beside children_from.
Source§fn extend<I: IntoIterator<Item = N>>(&mut self, iter: I)
fn extend<I: IntoIterator<Item = N>>(&mut self, iter: I)
Source§fn extend_one(&mut self, item: T)
fn extend_one(&mut self, item: T)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)Source§impl Render for Element
impl Render for Element
Source§fn write_into(&self, out: &mut String, options: &RenderOptions, depth: usize)
fn write_into(&self, out: &mut String, options: &RenderOptions, depth: usize)
Source§fn render_pretty(&self) -> String
fn render_pretty(&self) -> String
Source§fn render_with(&self, options: &RenderOptions) -> String
fn render_with(&self, options: &RenderOptions) -> String
Auto Trait Implementations§
impl Freeze for Element
impl RefUnwindSafe for Element
impl Send for Element
impl Sync for Element
impl Unpin for Element
impl UnsafeUnpin for Element
impl UnwindSafe for Element
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more