rerb
rerb

Reputation: 65

How to turn text into DOM elements using Clojurescript? (And Om?)

In a ClojureScript/Om app, I have a DOM and a string of HTML.

How can I translate that string of HTML into elements I can insert into the DOM?

I've started down the path of parsing the HTML with hickory, planning to then process the hickory data to create DOM elements, but I think there must be a simpler way I'm overlooking.

(I don't need to validate the HTML, I can assume it's safe and valid enough.)

Upvotes: 1

Views: 2072

Answers (2)

Aleš Roubíček
Aleš Roubíček

Reputation: 5187

You don't need to parse the HTML string. It's unnecessary overhead. React/Om supports something like DOM's innerHTML property. Just set the prop this way:

(om.dom/div #js {:dangerouslySetInnerHTML #js {:__html "<b>Bold!</b>"}} nil)

If you work with plain DOM without Om, set the innerHTML property like:

(let [div (. js/document getElementById "elId")]
     (set! (. div -innerHTML) "<b>Bold!</b>"))

Upvotes: 3

sbensu
sbensu

Reputation: 1521

Aleš Roubíček answer is much better. I'll leave this un case it helps somebody.

Hickory offers a as-hiccup function. Hiccup uses Clojure data structures to represent HTML. You could feed those data structures to Clojurescript libraries that follow the same conventions:

  • Hiccups to generate regular DOM elements.
  • Sablono to generate React DOM elements and use with Om.

You could also use Kioo/Enfocus and instead of passing a file path, pass the string directly. This would be more direct and instead of using two libraries (Hickory + Sablono) you would use only one. The caveat is that Kioo and Enfocus follow the Enlive style of templating (which is great but has a learning curve) and the docs are focused on file paths and not strings (even though it is possible to pass strings).

Upvotes: 3

Related Questions