LazyHTML.Tree (LazyHTML v0.1.14)
View SourceThis module deals with HTML documents represented as an Elixir tree data structure.
Validity
Trees returned by LazyHTML.to_tree/2 are always valid. If you
build or change a tree yourself, you must make sure it is valid,
that is, it could be produced by parsing HTML. The tree is not
validated when serialized. For example, tag and attribute names
must not contain whitespace, / or >, comments must not contain
-->, and text in <script> or <style> must not contain its
own end tag. Otherwise, the serialized HTML may be parsed into
a different tree.
Summary
Functions
Performs a depth-first, post-order traversal of the given tree.
Same a postwalk/3, but with no accumulator.
Performs a depth-first, post-order traversal of the given tree.
Performs a depth-first, pre-order traversal of the given tree.
Serializes Elixir tree data structure as an HTML string.
Types
@type html_comment() :: {:comment, String.t()}
@type html_node() :: html_tag() | html_text() | html_comment()
@type html_tag() :: {String.t(), [html_attribute()], [html_node()]}
@type html_text() :: String.t()
@type t() :: [html_node()]
Functions
Performs a depth-first, post-order traversal of the given tree.
This function traverses the tree without modifying it, check postwalk/2 and
postwalk/3 if you need to modify the tree.
Same a postwalk/3, but with no accumulator.
@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.
Performs a depth-first, pre-order traversal of the given tree.
This function traverses the tree without modifying it, check postwalk/2 and
postwalk/3 if you need to modify the tree.
Serializes Elixir tree data structure as an HTML string.
Options
:skip_whitespace_nodes- whentrue, ignores text nodes that consist entirely of whitespace, usually whitespace between tags. Defaults tofalse.
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>"