How to pass edn to clojurescript from clojure without an ajax request (i.e. using a page created using hiccup)

I am developing RIA with clojure and clojurescript. Backend uses hiccup to generate the resulting html, e.g.

(html5 
[:head 
  (include-js "/js/my-cljs-generated.js")]
[:body ... ])

How can I pass edn (hashmap, vector, etc.) to clojurescript inside the resulting html, i.e. without making an ajax call?

I would like to make a hiccup to do something like this:

(include-edn 
   "var_name" {:foo :bar}) ; or any other clojure data

and have access to past edn from cljs in some way (e.g. by name).

Currently my implementation is a bit hacky and stores edn in global js var

(hiccup/javascript-tag (str "var edn = \""
                       (pr-str my-clojure-data) "\";"))        

and on the side of cljs does something like

(jayq/document-ready 
  (fn []
    (if-let [edn (.-edn js/window)]
      (do-something-with (cljs.reader/read-string edn))
    )
    ...
)

Maybe there is a more idiomatic way to achieve this?

+5
source share
3 answers

. JavaScript, pr-str . - :

[:div {:style {:display "hidden"}
       :id "server-originated-data"
       :data-var-1 (pr-str var-1)
       :data-var-2 (pr-str var-2)}]

ClojureScript - :

(defn get-data
  [tag]
  (-> (.getElementById js/document "server-originated-data")
      (.getAttribute (str "data-" tag))
      (cljs.reader/read-string)))

, , .

+2

"" . , :)

, , . ClojureScript; - .

+1

push (event-based), pull: edn [: script] javascript clojurescript. script, edn , .

This will be a little more idiomatic than your current approach, as it does not require state or global data and can be easily adapted to use ajax later if necessary.

+1
source

All Articles