diff options
author | Hayleigh Thompson <me@hayleigh.dev> | 2024-03-17 19:09:58 +0000 |
---|---|---|
committer | Hayleigh Thompson <me@hayleigh.dev> | 2024-03-17 19:09:58 +0000 |
commit | e485db0b4f53e56ab285dad799e78b32463122e3 (patch) | |
tree | d9bfbb91606f0f2c8530d0903924a95af3085888 | |
parent | c66823a7e7cad7131b8a6a1bd946fafaf01aa846 (diff) | |
download | lustre-e485db0b4f53e56ab285dad799e78b32463122e3.tar.gz lustre-e485db0b4f53e56ab285dad799e78b32463122e3.zip |
:sparkles: Add to_document_string and to_document_string_builder functions that includes doctype declaration.
-rw-r--r-- | src/lustre/element.gleam | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/lustre/element.gleam b/src/lustre/element.gleam index 1c5c191..d02ccbb 100644 --- a/src/lustre/element.gleam +++ b/src/lustre/element.gleam @@ -235,6 +235,24 @@ pub fn to_string(element: Element(msg)) -> String { vdom.element_to_string(element) } +/// Converts an element to a string like [`to_string`](#to_string), but prepends +/// a `<!doctype html>` declaration to the string. This is useful for rendering +/// complete HTML documents. +/// +/// If the provided element is not an `html` element, it will be wrapped in both +/// a `html` and `body` element. +/// +pub fn to_document_string(el: Element(msg)) -> String { + vdom.element_to_string(case el { + Element(tag: "html", ..) -> el + Element(tag: "head", ..) | Element(tag: "body", ..) -> + element("html", [], [el]) + + _ -> element("html", [], [element("body", [], [el])]) + }) + |> string.append("<!doctype html>\n", _) +} + /// Convert a Lustre `Element` to a `StringBuilder`. This is _not_ pretty-printed, /// so there are no newlines or indentation. If you need to pretty-print an element, /// reach out on the [Gleam Discord](https://discord.gg/Fm8Pwmy) or @@ -244,3 +262,21 @@ pub fn to_string(element: Element(msg)) -> String { pub fn to_string_builder(element: Element(msg)) -> StringBuilder { vdom.element_to_string_builder(element) } + +/// Converts an element to a `StringBuilder` like [`to_string_builder`](#to_string_builder), +/// but prepends a `<!doctype html>` declaration. This is useful for rendering +/// complete HTML documents. +/// +/// If the provided element is not an `html` element, it will be wrapped in both +/// a `html` and `body` element. +/// +pub fn to_document_string_builder(el: Element(msg)) -> StringBuilder { + vdom.element_to_string_builder(case el { + Element(tag: "html", ..) -> el + Element(tag: "head", ..) | Element(tag: "body", ..) -> + element("html", [], [el]) + + _ -> element("html", [], [element("body", [], [el])]) + }) + |> string_builder.prepend("<!doctype html>\n") +} |