Skip to content

Instantly share code, notes, and snippets.

@PascalLeMerrer
Last active February 18, 2021 17:26
Show Gist options
  • Save PascalLeMerrer/8a1345795537d9fb315105a99150a17d to your computer and use it in GitHub Desktop.
Save PascalLeMerrer/8a1345795537d9fb315105a99150a17d to your computer and use it in GitHub Desktop.
Elm + CustomElement whose HTML content is generated by Elm

Today (5/09/2018) only chrome supports customElements

They are coming to firefox

You’ll want to include the @webcomponents/custom-elements polyfill for browsers that don’t yet fully support custom elements.

If you are using Babel < 7.0 for transpiling, then you may need to use a shim to support extending HTMLElement:

import "@webcomponents/custom-elements/src/native-shim"

More info: https://leveljournal.com/server-rendered-html-in-elm

module Main exposing (Model, Msg(..), init, main, update, view)
import Browser
import Html exposing (..)
import Html.Attributes exposing (property, src)
import Html.Events exposing (onClick)
import Json.Encode as Encode
---- MODEL ----
type alias Model =
{ counter : Int
}
init : ( Model, Cmd Msg )
init =
( { counter = 0 }, Cmd.none )
---- UPDATE ----
type Msg
= Clicked
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
( { model | counter = model.counter + 1 }, Cmd.none )
---- VIEW ----
view : Model -> Html Msg
view model =
div []
[ img [ src "/logo.svg" ] []
, h1 [] [ text "Your Elm App is working, dude!" ]
, Html.node "slick-grid"
[ property "data" (Encode.string <| viewHtmlAsString model) ]
[]
, button [ onClick Clicked ] [ text "click me!" ]
]
viewHtmlAsString : Model -> String
viewHtmlAsString model =
"<ul><li>Some HTML injected by Elm. Counter = "
++ String.fromInt model.counter
++ "</li><ul>"
---- PROGRAM ----
main : Program () Model Msg
main =
Browser.element
{ view = view
, init = \_ -> init
, update = update
, subscriptions = always Sub.none
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment