Rendering HTML encoded Strings

Hi,

As a way to learn Elm I’m building a simple random quote application that I’ve previously built in JS. So far, I can receive a JSON response with the following format, and I’ve decoded the content field.

[
  {
    "ID": 1564,
    "title": "Henry Ford",
    "content":
      "<p>You can&#8217;t build a reputation on what you&#8217;re going to do.</p>\n",
    "link": "https://quotesondesign.com/henry-ford-4/"
  }
]

In JS I would be able to inject the content string into the DOM as HTML, taking care of the escaped codes, p-tags and other special characters. Is there a simple way in Elm to achieve the same effect?

Thanks :beer:

2 Likes

elm-community/html-extra provides innerHtml.
But be aware of the security implications (XSS) of doing this, especially if the content is user provided.
But since this is just a project for learning, this seems to be ok.

1 Like

Nice! If you don’t want to install the whole library this is the minimal example using Html.Attributes.property:

https://ellie-app.com/mfVsvN2tca1/0

module Main exposing (main)

import Html exposing (Html, p, text)
import Html.Attributes exposing (property)
import Json.Encode as Json

main : Html msg
main =
    p
        [ property "innerHTML"
            (Json.string "Hello <b>unsafe</b> <em>HTML</em>")
        ]
        []
2 Likes

Thanks @joakin. That’s super helpful.

Thanks @zinggi, I’ll check that out. :sunny:

1 Like

Hi, for anyone who currently has the same problem/question:
The html-extra library does not have the innerHtml method in its last version and the “innerHTML” html property does not work in Elm 0.19

Related issue and alternative solution here (using Html.Parser package):

3 Likes