Skip to main content

Element

Struct Element 

Source
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 &amp; chain.</p></div>"#
);

Implementations§

Source§

impl Element

Source

pub fn new(tag: impl Into<String>) -> Self

Creates an element with the given tag name.

Source

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>");
Source

pub fn tag(&self) -> &str

The tag name.

Source

pub fn attributes(&self) -> &[Attribute]

The attributes, in insertion order.

Source

pub fn content(&self) -> Option<&str>

The escaped text content, if any.

Source

pub fn children(&self) -> &[Node]

The child nodes.

Source

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());
Source

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());
Source

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>");
Source

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 &amp; 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&amp;y=2"));
assert_eq!(link.attribute("download"), Some(""));
assert_eq!(link.attribute("target"), None);
Source

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>");
Source

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 &amp; b").render(), "<p>a &amp; b</p>");
Source

pub fn child(self, child: impl Into<Node>) -> Self

Appends a child node.

Source

pub fn children_from<N: Into<Node>>( self, children: impl IntoIterator<Item = N>, ) -> Self

Appends several child nodes.

Source

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);
Source

pub fn add_attribute(self, attribute: Attribute) -> Self

Appends an attribute. Does not deduplicate.

Source

pub fn attr(self, key: impl Into<String>, value: impl AsRef<str>) -> Self

Appends key="value", escaping the value. Does not deduplicate.

Source

pub fn bool_attr(self, key: impl Into<String>) -> Self

Appends a boolean attribute, which renders as a bare key.

Source

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>"
);
Source

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\" />"
);
Source

pub fn data_attr(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self

Appends data-{key}="{value}".

Source

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.

Source

pub fn aria_attr(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self

Appends aria-{key}="{value}".

Source

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.

Source

pub fn set_id(self, id: impl AsRef<str>) -> Self

Sets id, replacing any existing one.

Source

pub fn set_style(self, style: impl AsRef<str>) -> Self

Sets style, replacing any existing one.

Source

pub fn set_role(self, role: impl AsRef<str>) -> Self

Sets role, replacing any existing one.

Source

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.

Source

pub fn add_classes<S: AsRef<str>>( self, class_names: impl IntoIterator<Item = S>, ) -> Self

Appends several class names.

Trait Implementations§

Source§

impl Clone for Element

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
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.

§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§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Element

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

The compact render, or the pretty one with the alternate flag: {el} / {el:#}.

Source§

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.

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more
Source§

fn pin_drop(self: Pin<&mut Self>)

🔬This is a nightly-only experimental API. (pin_ergonomics)
Execute the destructor for this type, but different to Drop::drop, it requires self to be pinned. Read more
Source§

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.

Source§

fn extend<I: IntoIterator<Item = N>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<Element> for Node

Source§

fn from(element: Element) -> Self

Converts to this type from the input type.
Source§

impl Hash for Element

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for Element

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Render for Element

Source§

fn write_into(&self, out: &mut String, options: &RenderOptions, depth: usize)

Writes this node and its subtree into an existing buffer. Read more
Source§

fn render(&self) -> String

Renders as a single line of markup. Read more
Source§

fn render_pretty(&self) -> String

Renders with indentation and line breaks.
Source§

fn render_with(&self, options: &RenderOptions) -> String

Renders with the given options.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<S, T> Upcast<T> for S
where T: UpcastFrom<S> + ?Sized, S: ?Sized,

Source§

fn upcast(&self) -> &T
where Self: ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider ref type within the Wasm bindgen generics type system. Read more
Source§

fn upcast_into(self) -> T
where Self: Sized + ErasableGeneric, T: Sized + ErasableGeneric<Repr = Self::Repr>,

Perform a zero-cost type-safe upcast to a wider type within the Wasm bindgen generics type system. Read more