LazyHTML.Tree (LazyHTML v0.1.3)

View Source

This module deals with HTML documents represented as an Elixir tree data structure.

Summary

Functions

Same a postwalk/3, but with no accumulator.

Performs a depth-first, post-order traversal of the given tree.

Serializes Elixir tree data structure as an HTML string.

Types

html_attribute()

@type html_attribute() :: {String.t(), String.t()}

html_comment()

@type html_comment() :: {:comment, String.t()}

html_node()

@type html_node() :: html_tag() | html_text() | html_comment()

html_tag()

@type html_tag() :: {String.t(), [html_attribute()], [html_node()]}

html_text()

@type html_text() :: String.t()

t()

@type t() :: [html_node()]

Functions

postwalk(tree, fun)

@spec postwalk(t(), (html_node() -> html_node() | [html_node()])) :: t()

Same a postwalk/3, but with no accumulator.

postwalk(tree, acc, fun)

@spec postwalk(
  t(),
  acc,
  (html_node(), acc -> {html_node() | [html_node()], acc})
) :: {t(), acc}
when acc: term()

Performs a depth-first, post-order traversal of the given tree.

The mapper fun can return a list of nodes to replace the given node. In order to remove a node, return an empty list.

to_html(tree, opts \\ [])

@spec to_html(
  t(),
  keyword()
) :: String.t()

Serializes Elixir tree data structure as an HTML string.

Options

  • :skip_whitespace_nodes - when true, ignores text nodes that consist entirely of whitespace, usually whitespace between tags. Defaults to false.

Examples

iex> tree = [
...>   {"html", [], [{"head", [], [{"title", [], ["Page"]}]}, {"body", [], ["Hello world"]}]}
...> ]
iex> LazyHTML.Tree.to_html(tree)
"<html><head><title>Page</title></head><body>Hello world</body></html>"

iex> tree = [
...>   {"div", [], []},
...>   {:comment, " Link "},
...>   {"a", [{"href", "https://elixir-lang.org"}], ["Elixir"]}
...> ]
iex> LazyHTML.Tree.to_html(tree)
~S|<div></div><!-- Link --><a href="https://elixir-lang.org">Elixir</a>|

iex> tree = [
...>   {"p", [],
...>    [
...>      "\n  ",
...>      {"span", [], [" Hello "]},
...>      "\n  ",
...>      {"span", [], [" world "]},
...>      "\n"
...>    ]},
...>   "\n"
...> ]
iex> LazyHTML.Tree.to_html(tree, skip_whitespace_nodes: true)
"<p><span> Hello </span><span> world </span></p>"