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 text(self, content: impl AsRef<str>) -> Self

Sets the text content, escaping it.

Replaces any content already set.

Source

pub fn raw_text(self, content: impl Into<String>) -> Self

Sets the text content without escaping it.

The documented escape hatch for markup you already trust. <script> and <style> use this by default.

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.

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

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