ratchet v0.4.1 Ratchet.Template

Handles Ratchet data during EEx rendering

Summary

Functions

Extract attributes from a data property

Extract content from a data property

Determines if the given data provides plain text content

Prepares data for list comprehension

Get the specified property from the given data

Functions

attributes(data_attrs, elem_attrs)

Extract attributes from a data property

iex> Template.attributes({"", href: "https://google.com", rel: "nofollow"}, [])
{:safe, ~S(href="https://google.com" rel="nofollow")}
iex> Template.attributes([href: "/"], [{"data-prop", "link"}])
{:safe, ~S(href="/" data-prop="link")}
iex> Template.attributes([{"foo", href: "/"}], [{"data-prop", "link"}])
{:safe, ~S(data-prop="link")}
iex> Template.attributes("lolwat", [{"data-prop", "joke"}])
{:safe, ~S(data-prop="joke")}
iex> Template.attributes({:safe, "lolwat"}, [{"lol", "wat"}])
{:safe, ~S(lol="wat")}
content(content)

Extract content from a data property

iex> Template.content("text")
"text"
iex> Template.content(123)
123
iex> Template.content({"text", []})
"text"
iex> Template.content({:safe, "<p>lolwat</p>"})
{:safe, "<p>lolwat</p>"}
iex> Template.content({{:safe, "<p>lolwat</p>"}, []})
{:safe, "<p>lolwat</p>"}
content?(map)

Determines if the given data provides plain text content

iex> Template.content?("text")
true
iex> Template.content?({"text", href: "/foo/bar"})
true
iex> Template.content?(123)
true
iex> Template.content?({:safe, "<p>lolwat</p>"})
true
iex> Template.content?([href: "/"])
false
iex> Template.content?(%{foo: "bar"})
false
iex> Template.content?({%{foo: "bar"}, action: "/baz"})
false
iex> Template.content?(nil)
false
prepare(data)

Prepares data for list comprehension

Ratchet must be able to consistently treat data as a list to facilitate rendering multiple elements. This function supports that requirement by ensuring elements are wrapped in a list.

iex> Template.prepare("data")
["data"]
iex> Template.prepare(["one", "two"])
["one", "two"]
iex> Template.prepare([href: "/"])
[[href: "/"]]
iex> Template.prepare([{"foo", href: "/"}])
[{"foo", href: "/"}]
iex> Template.prepare({"foo", class: "btn"})
[{"foo", class: "btn"}]
iex> Template.prepare(nil)
[nil]
property(map, property)

Get the specified property from the given data

Data is defined in the following forms:

  1. A map of property keys to data values
  2. A tuple who’s first element is such a map and second element is data attributes
  3. Something else…

This function provides a consistent interface for fetching a property from some body of data.

iex> Template.property(%{}, :foo)
nil
iex> Template.property(%{foo: "bar"}, :foo)
"bar"
iex> Template.property({%{foo: "bar"}, []}, :foo)
"bar"
iex> Template.property({"Content", []}, :foo)
nil
iex> Template.property([attr: "value"], :foo)
nil