How to create structured data in Elm

I need something like this one. https://github.com/bentaylor2/react-structured-data

lets say that I wanna add other attributes to div.
like:

  <div itemprop="address" itemscope itemtype="http://schema.org/PostalAddress">
    <span itemprop="streetAddress">Rua Rui Barbosa, 710</span>

Do I need to create a port for JS?

Nope, you can just use Html.Attributes.attribute.


itemProp : String -> Html.Attribute msg
itemProp =
    Html.Attributes.attribute "itemprop"


itemType : String -> Html.Attribute msg
itemType =
    Html.Attributes.attribute "itemtype"


boolAttribute : String -> Bool -> Html.Attribute msg
boolAttribute attrName isPresent =
    if isPresent then
        Html.Attributes.attribute attrName ""

    else
        Html.Attributes.property attrName (Json.Encode.bool False)


itemScope : Bool -> Html.Attribute msg
itemScope =
    boolAttribute "itemscope"


address =
    div [ itemProp "address", itemScope True, itemType "http://schema.org/PostalAddress" ]
        [ span [ itemProp "streetAddress" ] [ text "Rua Rui Barbosa, 710" ]
        ]

see it running here: https://ellie-app.com/9gMKM5pyGHxa1

3 Likes

Maybe you can do something like:

Html.node "script"
    [ Html.Attributes.type_ "application/ld+json" ]
    [ Html.text (Json.Encode.encode 2 (makeLdJson model)) ]

(Where makeLdJson is some function that takes your model (or whatever) and produces some Json.Encode.Value.)

Then you don’t have to sprinkle all of it into your view.

1 Like

Is possibility to add this node to the scope of head markup?

Like that:

<head>
<script></script>
</head>

Thanks, my friends, I’m new in the language and I’m still a little confused.

I added built in support for JSON-LD tags to elm-pages recently.It’s prerendered in <script> tags: https://package.elm-lang.org/packages/dillonkearns/elm-pages/latest/Head#structuredData.

Not sure if that fits with your use case or not. Under the hood, I use ports to add the tags and then pre-render the pages with puppeteer.

1 Like

You can’t change the head of a document directly using Elm, but you can do so using ports.

1 Like

Addtional to the other answers, the <script> tag is always (including within the <body>) filtered out (found on stackoverflow)

On the other hand this official doc states, that there is script available.

1 Like

Also note that json-ld can be placed in <body> just fine:

https://developers.google.com/search/docs/guides/intro-structured-data

A JavaScript notation embedded in a <script> tag in the page head or body.

1 Like

Oh, I didn’t know this!

There’s seems to be a hacky workaround: https://github.com/elm/virtual-dom/issues/168

2 Likes

Heh, it’s good one :smiley:

I will use the server-side rendering, but your code was really helpful.

Thnx everybody for help.

1 Like