jgrenat / datocms-structured-text / StructuredText.Html

Once your DAST document is parsed from JSON, you get an opaque StructuredText value that you then need to render into HTML.

This is what the render method is for! But we need a little help from you to render the blocks, inline items and item links nodes. That's what you need to provide RenderParameters. If you don't have any custom item in your document, you can use the emptyRenderParameters.


type alias RenderParameters a msg =
{ renderBlock : a -> Html msg
, renderInlineItem : a -> Html msg
, renderItemLink : ItemLinkData a -> List (Html msg) -> Html msg 
}

Those parameters allow us to know how to render blocks, inline items and item links nodes.

If you don't use any or all those types, you can start from the emptyRenderParameters

The second argument is a list of children nodes.

type alias ImageItem =
    { url : String
    , alt : String
    }

renderParameters : RenderParameters imageItem msg
renderParameters =
    { renderBlock =
        \imageItem ->
            div [ class "image-block" ] [ img [ src imageItem.url, alt imageItem.alt ] [] ]
    , renderInlineItem =
        \imageItem ->
            img [ src imageItem.url, alt imageItem.alt, class "inline-image" ] []
    , renderItemLink =
        \itemLinkData children ->
            a [ href itemLinkData.item.url ] children
    }


type alias ItemLinkData a =
{ item : a
, meta : List ( String
, String ) 
}

Parameters that you receive when rendering an item link. meta is a list of key-value pairs provided in DatoCMS.

type alias ImageItem =
    { url : String
    , alt : String
    }

renderParameters : RenderParameters imageItem msg
renderParameters =
    { emptyRenderParameters
        | renderItemLink =
            \itemLinkData children ->
                let
                    metaAttributes =
                        List.map (\( key, value ) -> Html.attribute key value) itemLinkData.meta
                in
                a (href itemLinkData.item.url :: metaAttributes) children
    }

render : RenderParameters a msg -> StructuredText a -> List (Html msg)

Render a StructuredText document as elm/html nodes

main =
    Decode.decodeString myFieldDecoder myJsonDastDocument
        |> Result.map (StructuredText.Decode.render imageItemRenderParameters)
        |> Result.withDefault (text "Invalid document")

emptyRenderParameters : RenderParameters a msg

Default renderParameters that basically do nothing.