How to incorporate a string of HTML mark-up

I am moving my first elm application to elm-spa.
I’d like to incorporate a page of HTML that previously stood apart from my elm code.

Its layout is a little more than markdown enables so I’m looking for a way to get it into my elm-spa-based application:

view : Model -> View Msg
view model =
    { title = "Notes"
    , body =
        UI.layout
            [ UI.h1 "Notes"
            , -- I'd like to place it here
            ]
    }

I’ve tried node "inner-html" [ attribute "content" content ] [] but, while this adds my content to the page source, it’s not displayed.

I don’t think there’s an easy way to do that since Elm 0.19

Update

1 Like

You can still use the elm-markdown with sanitize = False, and it will just render the HTML that you give it, assuming it’s just markdown html (no script tags for example). Since it’s your own HTML, turning sanitization off is much less risky.

Another possibility is to use an iframe with the srcdoc attribute.

3 Likes

A web component is a robust option:

class HtmlView extends HTMLElement {
    constructor() {
        super()
        this._html = ""
    }

    get html() {
        return this.shadow ? this.shadow.innerHTML : this._html
    }

    set html(value) {
        this._html = value
        if (this.shadow)
            this.shadow.innerHTML = value
    }
    connectedCallback() {
        this.shadow = this.attachShadow({ mode: 'closed' })
        this.shadow.innerHTML = this._html
    }
}

window.customElements.define('html-view', HtmlView);

This one uses the closed shadow DOM to prevent any CSS from leaking in/out, but you may equally let it open depending on your need.

And then in Elm:

module Html.HtmlView exposing (view)

import Html exposing (Attribute, Html, node)
import Html.Attributes exposing (property)
import Json.Encode


view : List (Attribute msg) -> String -> Html msg
view attributes html =
    node "html-view" ((property "html" <| Json.Encode.string html) :: attributes) []

Of course, if you don’t like view as a name, change it, maybe to rawHtml or something else you prefer.

Finally use it like so in your code:

Html.HtmlView.view [] "<html/>"
6 Likes

I compared pablohirafuji/elm-markdown with hecrj/html-parser purely for performance, I might add. The latter felt like native performance when tapping between my tabs of content whereas the HTML parser, paused shortly, before updating the content.

The key to configuring elm-markdown was to set defaultOptions to Markdown.Config.ParseUnsafe which enabled anchor tags to be rendered correctly.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.