View Source Pile (pile v0.9.0)
This library allows representing HTML in Elixir. It uses tuples to represent elements, and maps to represent element attributes:
iex> {:html,
...> {:head,
...> {:title, "Hello World"},
...> {:link, %{rel: "stylesheet", href: "..."}},
...> }
...> }
...> |> Pile.to_html()
...>
"<html><head><title>Hello World</title><link rel=\"stylesheet\" href=\"...\"></head></html>"
See Pile.to_html/2
for more details about the syntax
Summary
Functions
Converts a tuple (or a list of tuples) into an HTML string
Functions
to_html(input, opts \\ [pretty: false, doctype: false, iodata: false])
View SourceConverts a tuple (or a list of tuples) into an HTML string
Options:
pretty
: Passingtrue
causes the HTML output to be pretty-printed. Defaults tofalse
.doctype
: Prepend the<!DOCTYPE html>
to the resulting string. Defaults tofalse
.iodata
: Return the HTML as iodata. Defaults tofalse
.
Syntax:
A tuple begining with an atom represents an HTML element:
iex> {:div} |> Pile.to_html()
"<div></div>"
Elements can have children:
iex> {:div, {:p}, {:p}} |> Pile.to_html()
"<div><p></p><p></p></div>"
Lists are automatically flattened, which is particularly useful for iteration & composition:
iex> {:div,
...> {:p},
...> 1..2 |> Enum.map(fn _ -> {:span} end)
...> } |> Pile.to_html()
"<div><p></p><span></span><span></span></div>"
Strings are HTML-escaped, then rendered as text:
iex> {:div, "hello"} |> Pile.to_html()
"<div>hello</div>"
iex> {:div, "<span>"} |> Pile.to_html()
"<div><span></div>"
To bypass HTML escaping, using the special _rawtext
element:
iex> {:div, {:_rawtext, "<span>"}} |> Pile.to_html()
"<div><span></div>"
Elements may have attributes. These are represented as a map, and if present must come right after the element name:
iex> {:div, %{class: "container"}} |> Pile.to_html()
"<div class=\"container\"></div>"
iex> {:div, %{class: "container"}, "foo", {:p}} |> Pile.to_html()
"<div class=\"container\">foo<p></p></div>"
An attribute with a boolean value is treated as an HTML boolean attribute
iex> {:div, %{readonly: true}} |> Pile.to_html()
"<div readonly></div>"
iex> {:div, %{readonly: false}} |> Pile.to_html()
"<div></div>"