specter

Latest version: 1.1.3
2018-01-19T16:12:16.000402Z

Hey guys, I wanted to share how I am finally going about “splicing” some tags in a html tree. I realize I hadn’t properly formulated my problem... Anyway here’s the code:

(require '[com.rpl.specter :as sp])
(require '[com.rpl.specter.zipper :as spz])
(require '[clojure.zip :as zip])

(def tag-to-unwrap :tag-to-unwrap)
(defn tag-to-unwrap? [t] (= (:tag t) tag-to-unwrap))
(defn tag?-to-unwrap? [t] (and (map? t) (tag-to-unwrap? t)))

(def TAGS-TO-UNWRAP (sp/path [spz/XML-ZIP spz/NEXT-WALK
(sp/selected? [spz/NODE tag?-to-unwrap?])]))

(defn unwrap [zipper]
(let [cs (zip/children zipper)
zipper (reduce zip/insert-right zipper (reverse cs))]
(zip/remove zipper)))

(defn splice-doc [doc]
(sp/transform TAGS-TO-UNWRAP unwrap doc))

(splice-doc
{:tag :body
:content ["toto"
{:tag tag-to-unwrap :content ["titi" "tutu"]}
{:tag :div
:content [{:tag tag-to-unwrap :content ["toto in a div"]}]}]})
;=>
{:tag :body, :content ["toto" "titi" "tutu" {:tag :div, :content ["toto in a div"]}]}

2018-01-19T16:12:22.000237Z

cheers

👍 1