DatoCMS GraphQL Client

Initialization

In config/config.exs:

config :my_app,
api_key: System.get_env("DATOCMS_API_KEY")
datocms_api_key = Application.fetch_env!(:my_app, :api_key)
DatoCMS.GraphQLClient.configure(api_key: datocms_api_key)

Queries

Structured Text

DatoCMS structured text fields are complex, and rendering them as HTML is hard.

This library provides the helper DatoCMS.StructuredText.to_html/2, which takes the structured text part of a GraphQL response and transforms it into HTML.

The default rendering turns this:

{
"value": {
"schema": "dast",
"document": {
"type": "root",
"children": [
{
"type": "paragraph",
"children": [
{
"type": "span",
"value": "Hi There"
}
]
}
]
}
}
}

with this:

DatoCMS.StructuredText.to_html(structured_text)

into this:

<p>Hi There</p>

By default, the types are transformed as follows:

typeresult
rootthe rendered children
paragraph<p>...</p>
spanthe node value
heading<hn>...</hn> where n is the level
link<a ...>...</a>
blockrequires custom renderer (see below)
inlineItemrequires custom renderer (see below)
itemLinkrequires custom renderer (see below)

Note that text styling is transformed as follows:

marktag
codecode
emphasisem
highlightmark
strikethroughdel
strongstrong
underlineu

Optional Custom Renderers

All of these types of rendering can be overriden.

This is achieved by passing custom renderers in the second options parameter:

import DatoCMS.StructuredText, only: [to_html: 2, render: 3]
def custom_paragraph(node, _dast, _options) do
["<section>"] ++
Enum.map(node.children, &(render(&1, dast, options))) ++
["</section>"]
end
options = %{
renderers: %{
render_paragraph: &custom_paragraph/3
}
}
result = to_html(structured_text, options)

Note: custom renderers need to return a list of strings.

The custom renderers that can be used in this way are the following:

Required Renderers

If your structured text includes blocks, inline items or item links, you'll need to supply a custom renderer.